Source From Here
Question
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 a file. Because the output is sometimes large enough to overwhelm subprocess.PIPE, causing the script to hang, I send the stdout directly to the log file. I want to have my script write something to the beginning and end of the file, and between the two subprocess.PIPE calls. However, when I look at my log file, anything I wrote to the log file from the script is all together at the top of the file, followed by all the executable stdout. How can I interleave my added text to the file?
How-To
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:
Supplement
* How do I redirect stdout to a file when using subprocess.call in python?
Question
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 a file. Because the output is sometimes large enough to overwhelm subprocess.PIPE, causing the script to hang, I send the stdout directly to the log file. I want to have my script write something to the beginning and end of the file, and between the two subprocess.PIPE calls. However, when I look at my log file, anything I wrote to the log file from the script is all together at the top of the file, followed by all the executable stdout. How can I interleave my added text to the file?
- def run(cmd, logfile):
- p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)
- return p
- def runTest(path, flags, name):
- log = open(name, "w")
- 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"
- log.close()
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
* How do I redirect stdout to a file when using subprocess.call in python?
- with open('out-file.txt', 'w') as f:
- subprocess.call(['program'], stdout=f)
沒有留言:
張貼留言