How can I print and display subprocess stdout and stderr output without distortion?

后端 未结 3 1842
野性不改
野性不改 2020-12-01 13:30

Maybe there\'s someone out in the ether that can help me with this one. (I have seen a number of similar questions to this on SO, but none deal with both standard out and st

3条回答
  •  囚心锁ツ
    2020-12-01 13:47

    When I tested it, it seemed readline() is blocking. However I was able to access stdout and stderr separately using threads. Code sample as follows:

    import os
    import sys
    import subprocess
    import threading
    
    class printstd(threading.Thread):
        def __init__(self, std, printstring):
            threading.Thread.__init__(self)
            self.std = std
            self.printstring = printstring
        def run(self):
            while True:
              line = self.std.readline()
              if line != '':
                print self.printstring, line.rstrip()
              else:
                break
    
    pythonfile = os.path.join(os.getcwd(), 'mypythonfile.py')
    
    process = subprocess.Popen([sys.executable,'-u',pythonfile], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    print 'Process ID:', process.pid
    
    thread1 = printstd(process.stdout, 'stdout:')
    thread2 = printstd(process.stderr, 'stderr:')
    
    thread1.start()
    thread2.start()
    
    threads = []
    
    threads.append(thread1)
    threads.append(thread2)
    
    for t in threads:
        t.join()
    

    However, I am not certain that this is thread-safe.

提交回复
热议问题