read subprocess stdout line by line

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

    It's been a long time since I last worked with Python, but I think the problem is with the statement for line in proc.stdout, which reads the entire input before iterating over it. The solution is to use readline() instead:

    #filters output
    import subprocess
    proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
    while True:
      line = proc.stdout.readline()
      if not line:
        break
      #the real code does filtering here
      print "test:", line.rstrip()
    

    Of course you still have to deal with the subprocess' buffering.

    Note: according to the documentation the solution with an iterator should be equivalent to using readline(), except for the read-ahead buffer, but (or exactly because of this) the proposed change did produce different results for me (Python 2.5 on Windows XP).

提交回复
热议问题