Saving stdout from subprocess.Popen to file, plus writing more stuff to the file

后端 未结 4 1515
谎友^
谎友^ 2020-12-28 14:58

I\'m writing a python script that uses subprocess.Popen to execute two programs (from compiled C code) which each produce stdout. The script gets that output and saves it to

4条回答
  •  再見小時候
    2020-12-28 15:31

    You could call .wait() on each Popen object in order to be sure that it's finished and then call log.flush(). Maybe something like this:

    def run(cmd, logfile):
        p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)
        ret_code = p.wait()
        logfile.flush()
        return ret_code
    

    If you need to interact with the Popen object in your outer function you could move the .wait() call to there instead.

提交回复
热议问题