关于Python的subprocess.Popen()对象的问题
(请假设为stdout / stderr生成的字节数未填满OS管道缓冲区并创建等待OS管道缓冲区接受更多数据的死锁的情况)
1)p.stdout.read()和p.wait()的顺序是否重要?
2)在stdout / stderr subprocess.PIPE块上执行read()直到进程终止?
3)即使在进程终止后,stdout / stderr subprocess.PIPE文件对象和数据是否可用?
import subprocess
process = subprocess.Popen(args="ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout = process.stdout.read()
# Does the above read() block until the process has terminated?
stderr = process.stderr.read()
return_code = process.wait()
process = subprocess.Popen(args="ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
return_code = process.wait()
# Are stdout and stderr pipes available now, even after the process terminated?
stdout = process.stdout.read()
stderr = process.stderr.read()
2 回答
您可能需要考虑使用像_2825235这样的库,它允许在使用子进程执行I / O时具有灵活性 . (披露:我'm the maintainer. I wrote it partly in response to the kind of difficulties you'有 . )
问:p.stdout.read()和p.wait()的顺序是否重要?
答:没有 .
问:对stdout / stderr subprocess.PIPE块执行read()直到进程终止?
答:如果没有指定要读取的字节数限制,那么它将阻塞直到流关闭(这可能是进程终止时) .
问:即使在进程终止后,stdout / stderr subprocess.PIPE文件对象和数据是否可用?
答:是的 .
您可能需要特别注意
subprocess
文档中的此警告: