live output from subprocess command

后端 未结 16 1472
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 08:16

I\'m using a python script as a driver for a hydrodynamics code. When it comes time to run the simulation, I use subprocess.Popen to run the code, collect the

16条回答
  •  我在风中等你
    2020-11-22 09:03

    In addition to all these answer, one simple approach could also be as follows:

    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    
    while process.stdout.readable():
        line = process.stdout.readline()
    
        if not line:
            break
    
        print(line.strip())
    

    Loop through the readable stream as long as it's readable and if it gets an empty result, stop.

    The key here is that readline() returns a line (with \n at the end) as long as there's an output and empty if it's really at the end.

    Hope this helps someone.

提交回复
热议问题