live output from subprocess command

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

    It looks like line-buffered output will work for you, in which case something like the following might suit. (Caveat: it's untested.) This will only give the subprocess's stdout in real time. If you want to have both stderr and stdout in real time, you'll have to do something more complex with select.

    proc = subprocess.Popen(run_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    while proc.poll() is None:
        line = proc.stdout.readline()
        print line
        log_file.write(line + '\n')
    # Might still be data on stdout at this point.  Grab any
    # remainder.
    for line in proc.stdout.read().split('\n'):
        print line
        log_file.write(line + '\n')
    # Do whatever you want with proc.stderr here...
    

提交回复
热议问题