live output from subprocess command

后端 未结 16 1175
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    Based on all the above I suggest a slightly modified version (python3):

    • while loop calling readline (The iter solution suggested seemed to block forever for me - Python 3, Windows 7)
    • structered so handling of read data does not need to be duplicated after poll returns not-None
    • stderr piped into stdout so both output outputs are read
    • Added code to get exit value of cmd.

    Code:

    import subprocess
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT, universal_newlines=True)
    while True:
        rd = proc.stdout.readline()
        print(rd, end='')  # and whatever you want to do...
        if not rd:  # EOF
            returncode = proc.poll()
            if returncode is not None:
                break
            time.sleep(0.1)  # cmd closed stdout, but not exited yet
    
    # You may want to check on ReturnCode here
    

提交回复
热议问题