read subprocess stdout line by line

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

    Bit late to the party, but was surprised not to see what I think is the simplest solution here:

    import io
    import subprocess
    
    proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
    for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):  # or another encoding
        # do something with line
    

    (This requires Python 3.)

提交回复
热议问题