简体   繁体   English

有没有办法将输出打印到stdout并捕获?

[英]is there a way to print the output to stdout and capture as well?

I am executing a command which takes around 15mins, I capture the output through fetchPipe.communicate and then print it. 我正在执行大约15分钟的命令,我通过fetchPipe.communicate捕获了输出,然后将其打印出来。 Is there a way in Python to print the output to stdout and capture as well? Python中是否有办法将输出打印到stdout并捕获?

    fetchPipe = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (output, error) = fetchPipe.communicate()

Yes. 是。 An example for that could be using a listener function: Writing to stdout and triggering something upon line recieve 例如,可以使用侦听器功能:写入stdout并在收到行时触发一些操作

import sys
import subprocess
import threading

The listener 听众

def listener(proc):
     for line in proc.stdout:
         sys.stdout.write(line)
         triggerRecvLine(line)
     proc.wait()

It might be wise to run the listener in a different thread. 在其他线程中运行侦听器可能是明智的。

proc=subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
t = threading.Thread(target=listener, args=(proc, ))
t.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM