I am running the following piece of code (call it batch.py)
for config in keystoneConfig:
cmdlist = generate_cmd_list(config)
print ' '.join(cmdlist)
subprocess.call(cmdlist)
And redirecting the output of batch.py to another file. i.e.
./batch.py > output.txt
But I realize that all the output from subprocess.call()
goes before the print
statement. Why is the output out of sync?
To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.
subprocess. run() is synchronous which means that the system will wait till it finishes before moving on to the next command. subprocess. Popen() does the same thing but it is asynchronous (the system will not wait for it to finish).
The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.
Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.
Python is block buffering its own output and not flushing it before subprocess.call()
, because you redirected its output to a file instead of the console; you would need to force line buffering or disable buffering, or manually flush before the subprocess call.
Flush with sys.stdout.flush()
after printing and before making the subprocess call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With