我正在使用 subprocess.Popen
(POSIX 系统上的 Python 2.x)调用子进程。我希望能够使用 Python 的 readline() 文件对象函数读取子进程的输出。但是,Popen.stdout
中可用的流似乎没有 readline()
方法。
使用 Python readline from pipe on Linux 中的想法,我尝试了以下方法:
p = subprocess.Popen(
[sys.executable, "child.py"],
stdout=subprocess.PIPE)
status = os.fdopen(p.stdout.fileno())
while True:
s = status.readline()
if not s:
break
print s
但是,此方法的问题在于 p.stdout
对象和新的 status
对象都尝试关闭单个文件描述符。这最终导致:
close failed: [Errno 9] Bad file number
有没有办法创建一个文件对象来“包装”之前创建的类文件对象?
最佳答案
解决方案是使用os.dup()
创建另一个引用同一管道的文件描述符:
status = os.fdopen(os.dup(p.stdout.fileno()))
这样,status
就有自己的文件描述符来关闭。
关于python - 如何将 readline() 与 subprocess.Popen 返回的管道一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8661710/