如何从外部进程Python 2获取实时日志

时间:2018-01-20 15:57:08

标签: python subprocess

在“文档”文件夹中,创建文件夹temp

/My Documents/temp

将这几行保存为worker.py Python脚本:

import time 
from datetime import datetime
for i in range(10):
    print '%s...working on iteration %s' % (datetime.now(), i)
    time.sleep(0.2) 
print '\nCompleted!\n'

将以下代码保存为caller.py

import subprocess
cmd = ['python', 'worker.py']
stdout = subprocess.check_output(cmd)
print stdout

(请注意,两个Python脚本都保存在同一个文件夹中。)

现在使用OS X终端或Windows CMD窗口将当前目录更改为您创建的文件夹:

cd /My Documents/temp

现在运行:

python caller.py

此过程需要2秒钟才能完成。完成后,它会立即打印出整个进度日志:

2018-01-20 07:52:14.399679...working on iteration 0
...
2018-01-20 07:52:16.216237...working on iteration 9
Completed!

我希望有一个实时的进度更新,而不是打印日志(在进程完成后立即打印)。我希望在发生的同一时刻从过程中得到每条印刷线。 因此,当我运行python worker.py命令时,它将实时发生逐行更新。如何实现呢?

1 个答案:

答案 0 :(得分:1)

要从子流程获取实时Feed,您可以在caller.py中使用此代码

import time 
import subprocess

# Start worker process
p = subprocess.Popen(['python', '-u', 'worker.py'], stdout=subprocess.PIPE)

# Loop forever
while True:

    # Get new line value
    l = p.stdout.readline()

    # Stop looping if the child process has terminated
    if p.poll() is not None:
        break

    # Print the line
    print l

注意subprocess.Popen中的 -u ,你需要无缓冲的stdout。 https://docs.python.org/3/using/cmdline.html#cmdoption-u

使用readline(),您每次从子进程输出读取一行。请注意子进程何时打印&n;已完成!\ n'你将在三个循环中阅读它。 https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

在该示例中,循环将一直运行,直到子进程终止。 https://docs.python.org/3/library/subprocess.html#subprocess.Popen.poll