从子进程输出中读取 python
read from subprocess output python
我是 运行 使用 'Popen' 的子进程。我需要阻塞直到这个子进程完成,然后读取它的输出。
p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8")
p.communicate():
output = p.stdout.readline()
print(output)
我收到一个错误
ValueError: I/O operation on closed file.
如何在子进程完成后读取输出,我不想使用 poll(),因为子进程需要时间,而且无论如何我都需要等待它完成。
这应该有效:
p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8")
output, error = p.communicate()
print(output)
if error:
print('error:', error, file=sys.stderr)
然而,现在 subprocess.run()
更受欢迎:
p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("output:", p.stdout)
if proc.stderr:
print("error:", p.stderr, file=sys.stderr)
使用subprocess.check_output
。它returns命令的输出。
我是 运行 使用 'Popen' 的子进程。我需要阻塞直到这个子进程完成,然后读取它的输出。
p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8")
p.communicate():
output = p.stdout.readline()
print(output)
我收到一个错误
ValueError: I/O operation on closed file.
如何在子进程完成后读取输出,我不想使用 poll(),因为子进程需要时间,而且无论如何我都需要等待它完成。
这应该有效:
p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8")
output, error = p.communicate()
print(output)
if error:
print('error:', error, file=sys.stderr)
然而,现在 subprocess.run()
更受欢迎:
p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("output:", p.stdout)
if proc.stderr:
print("error:", p.stderr, file=sys.stderr)
使用subprocess.check_output
。它returns命令的输出。