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

后端 未结 4 1489
谎友^
谎友^ 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:40

    You need to wait until the process is finished before you continue. I've also converted the code to use a context manager, which is cleaner.

    def run(cmd, logfile):
        p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)
        p.wait()
        return p
    
    def runTest(path, flags, name):
        with open(name, "w") as log:
            print >> log, "Calling executable A"
            a_ret = run(path + "executable_a_name" + flags, log)
            print >> log, "Calling executable B"
            b_ret = run(path + "executable_b_name" + flags, log)
            print >> log, "More stuff"
    

提交回复
热议问题