Fix process lines iterator (#19605)

* Ensure lines when process done

* eliminate post-EOF exit test

* Recommend fixes for execCmdEx/execProcess
This commit is contained in:
Dominic Ward
2022-03-23 06:50:36 +00:00
committed by GitHub
parent 4c8934305c
commit a8b5ad845c

View File

@@ -451,7 +451,7 @@ proc execProcesses*(cmds: openArray[string],
if afterRunEvent != nil: afterRunEvent(i, p)
close(p)
iterator lines*(p: Process): string {.since: (1, 3), tags: [ReadIOEffect].} =
iterator lines*(p: Process, keepNewLines = false): string {.since: (1, 3), tags: [ReadIOEffect].} =
## Convenience iterator for working with `startProcess` to read data from a
## background process.
##
@@ -474,11 +474,11 @@ iterator lines*(p: Process): string {.since: (1, 3), tags: [ReadIOEffect].} =
## p.close
var outp = p.outputStream
var line = newStringOfCap(120)
while true:
if outp.readLine(line):
yield line
else:
if p.peekExitCode != -1: break
while outp.readLine(line):
if keepNewLines:
line.add("\n")
yield line
discard waitForExit(p)
proc readLines*(p: Process): (seq[string], int) {.since: (1, 3).} =
## Convenience function for working with `startProcess` to read data from a
@@ -514,6 +514,7 @@ when not defined(useNimRtl):
var outp = outputStream(p)
result = ""
var line = newStringOfCap(120)
# consider `p.lines(keepNewLines=true)` to circumvent `running` busy-wait
while true:
# FIXME: converts CR-LF to LF.
if outp.readLine(line):
@@ -1622,6 +1623,7 @@ proc execCmdEx*(command: string, options: set[ProcessOption] = {
inputStream(p).write(input)
close inputStream(p)
# consider `p.lines(keepNewLines=true)` to avoid exit code test
result = ("", -1)
var line = newStringOfCap(120)
while true: