简体   繁体   中英

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. Is there a way in Python to print the output to stdout and capture as well?

    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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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