管道到文件时分析subprocess.Popen的输出

时间:2014-12-11 10:40:40

标签: 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.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'

为什么p.stdout等于None

2 个答案:

答案 0 :(得分:2)

您必须使用subprocess.PIPE作为stdout参数才能获取文件对象。请将其None。这就是为什么p.stdout等于代码None的原因。

From the DOC

  

使用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

答案 1 :(得分:1)

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output,error=p.communicate()

现在你输出了错误。