Reputation: 1134
I am using subprocess to run a executable and piping the output of it using communicate. Finally, I write the contents of communicate to a file. The exact code is shown below
run = subprocess.Popen(['executable'], stdout=subprocess.PIPE)
output = run.communicate()[0]
logfile = open('run.log', 'a')
logfile.write(output)
logfile.close()
In the above process, the logfile is written at the end of the run. However, is there a way to write the output to the log as the executable is running?
Upvotes: 0
Views: 2041
Reputation: 1134
I think I found the solution to this:
logfile = ('run.log', 'w')
run = subprocess.Popen(['executable'], stdout = logfile)
run.wait()
logfile.close()
The first line creates the run.log
for writing and stdout
writes directly to the logfile as the executable is running. The run.wait()
waits for the executable to complete and then the log file is closed.
Upvotes: 0
Reputation: 180471
You mean something like:
with open("run.log","a") as f:
run = subprocess.Popen(['executable'], stdout=f)
Upvotes: 2