【问题标题】:Problem with capaturing Python output from a Python script containing subprocess.call()从包含 subprocess.call() 的 Python 脚本捕获 Python 输出的问题
【发布时间】:2019-02-20 08:24:00
【问题描述】:

这是我的问题。尝试捕获 Python 输出时,subprocess.call() 输出错误地出现在 print() 输出之前。我在 Windows 10 上使用 Python 3.7.2 从命令窗口运行 Python。

这是一个说明问题的小例子:

import subprocess

print("test")
subprocess.call("where python",shell=True)

注意 print() 输出应该在 subprocess.call() 输出之前。

这是我在不捕获输出的情况下运行时得到的结果:

c:\Users\GeoffAlexander\Documents\Python>python test.py
test
C:\Users\GeoffAlexander\AppData\Local\Programs\Python\Python37-32\python.exe>
c:\Users\GeoffAlexander\Documents\Python>

print() 输出正确地出现在 subprocess.call() 输出之前。

但是,当我将输出重定向到文件时,我得到的结果如下:

c:\Users\GeoffAlexander\Documents\Python>python test.py > test.out

c:\Users\GeoffAlexander\Documents\Python>cat test.out
C:\Users\GeoffAlexander\AppData\Local\Programs\Python\Python37-32\python.exe
test

c:\Users\GeoffAlexander\Documents\Python>

注意 subprocess.call() 输出错误地出现在 print() 输出之前。

为什么会这样?如何以正确的顺序捕获 Python 输出?

【问题讨论】:

    标签: python


    【解决方案1】:

    如何以正确的顺序捕获 Python 输出?

    你好,

    在你的 print 调用之后尝试刷新你的标准输出,比如:

    import subprocess
    import sys
    
    print("test")
    sys.stdout.flush()
    subprocess.call("echo python",shell=True)
    

    输出正确(在Linux系统上测试):

    $ python test.py
    test
    python
    $ python test.py > filename
    $ cat filename
    test
    python
    

    【讨论】:

    • 感谢您的建议。它在 Windows 上也适用于我。为了完整起见,我怀疑我也应该刷新标准错误。这适用于我编写(或可以更改)的 Python 脚本。但对于其他人编写的较大脚本,进行此类更改可能会出现问题。
    【解决方案2】:

    你需要通过管道与子进程通信

    请参阅https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python 了解示例

    【讨论】:

    • 尝试复制/粘贴相关代码以防链接过期
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 2018-03-07
    • 2015-04-26
    • 2015-12-21
    • 1970-01-01
    • 2022-11-25
    • 2018-11-01
    相关资源
    最近更新 更多