read subprocess stdout line by line

后端 未结 9 2258
一个人的身影
一个人的身影 2020-11-22 02:15

My python script uses subprocess to call a linux utility that is very noisy. I want to store all of the output to a log file and show some of it to the user. I thought the

9条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 02:37

    I tried this with python3 and it worked, source

    def output_reader(proc):
        for line in iter(proc.stdout.readline, b''):
            print('got line: {0}'.format(line.decode('utf-8')), end='')
    
    
    def main():
        proc = subprocess.Popen(['python', 'fake_utility.py'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
    
        t = threading.Thread(target=output_reader, args=(proc,))
        t.start()
    
        try:
            time.sleep(0.2)
            import time
            i = 0
    
            while True:
            print (hex(i)*512)
            i += 1
            time.sleep(0.5)
        finally:
            proc.terminate()
            try:
                proc.wait(timeout=0.2)
                print('== subprocess exited with rc =', proc.returncode)
            except subprocess.TimeoutExpired:
                print('subprocess did not terminate in time')
        t.join()
    

提交回复
热议问题