read subprocess stdout line by line

后端 未结 9 2077
一个人的身影
一个人的身影 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:45

    The following modification of Rômulo's answer works for me on Python 2 and 3 (2.7.12 and 3.6.1):

    import os
    import subprocess
    
    process = subprocess.Popen(command, stdout=subprocess.PIPE)
    while True:
      line = process.stdout.readline()
      if line != '':
        os.write(1, line)
      else:
        break
    

提交回复
热议问题