subprocess.Popen() stdout and stderr handling



如何处理进程标准?

proc = subprocess.Popen('ll'.split(), stdout=subprocess.PIPE)
for i in proc.stdout:
print(i)

现在我正在流式传输输出,但我不确定如何正确处理可能发生的潜在错误。

我想使用out, err = proc.communicate()但我的out可能是一个非常非常长的字符串

如果您知道会发生什么错误消息,那么一个答案是将subprocess.STDOUT传递给Popenstderr参数,以便您的 stderr 消息位于 stdout 流中:

proc = subprocess.Popen('ll'.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for i in proc.stdout:
print(i)
# check for error message strings and do something with them

或者,如果您不关心标准输出消息,那么只需迭代 stderr:

dnull = open(os.devnull, 'w')
proc = subprocess.Popen('ll'.split(), stdout=dnull, stderr=subprocess.PIPE)
for i in proc.stderr:
print(i)
# check for error message strings and do something with them

最新更新