Python 将管道传输到文件时分析subprocess.Popen的输出
如何在写入文件时实时分析命令(通过管道传输到文件)的输出 这就是我到目前为止所做的:Python 将管道传输到文件时分析subprocess.Popen的输出,python,Python,如何在写入文件时实时分析命令(通过管道传输到文件)的输出 这就是我到目前为止所做的: with open('output.log', 'w') as out: command = ['pg_dump', 'myDB'] p = subprocess.Popen(cmd, stdout=out, stderr=subprocess.STDOUT) for line in iter(p.stdout.readline, b''): sys.stdout.fl
with open('output.log', 'w') as out:
command = ['pg_dump', 'myDB']
p = subprocess.Popen(cmd, stdout=out, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
sys.stdout.flush()
print(">>> " + line.rstrip())
但这会产生以下错误:
Traceback (most recent call last):
File "pipe-to-file.py", line 95, in <module>
for line in iter(p.stdout.readline, b''):
AttributeError: 'NoneType' object has no attribute 'readline'
回溯(最近一次呼叫最后一次):
文件“pipe to File.py”,第95行,在
对于iter中的线路(p.stdout.readline,b''):
AttributeError:“非类型”对象没有属性“readline”
为什么p.stdout
在这里等于None
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output,error=p.communicate()
现在您有了输出,error。您必须对
stdout
参数使用subprocess.PIPE
,以获取文件对象,否则它将是None
。这就是为什么p.stdout
在代码中等于None
使用communicate()
而不是.stdin.write
、.stdout.read
或.stderr.read
,以避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致死锁
如果您想在分析输出时将stdout
写入一个文件,那么您可以使用类似的方法
with open('log', 'ab+') as out:
p = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
std_out, std_error = p.communicate()
# Do something with std_out
# ...
# Write to the file
out.write( std_out )
# You can use `splitlines()` to iterate over the lines.
for line in std_out.splitlines():
print line
一旦过程完成,使用communicate()
将给出结果。只需像OP那样读取p.stdout
,但使用subprocess.PIPE
像您一样传递。