Reputation: 8145
I am using the following code to redirect my print statements into a text file.
old_stdout = sys.stdout
log_file = open("message.log","w")
sys.stdout = log_file
print "this will be written to message.log"
subprocess.call("iPython.exe", "script.py") #subprocesses here take this form
sys.stdout = old_stdout
log_file.close()
My problem is that this does not seem to apply to subprocesses. The print statements in "script.py" will not appear in "message.log". How can I make it so that they do?
Upvotes: 0
Views: 127
Reputation: 4762
Use subprocess.Popen
instead of subprocess.call
, which allows you to redirect stdout
and stderr
.
import subprocess
with (open('message_stdout.log', 'w'), open('message_stderr.log', 'w')) as (stdout_file, stderr_file):
my_process = subprocess.Popen(["iPython.exe", "script.py"],
stdout=stdout_file,
stderr=stderr_file)
You can also redirect stderr to stdout like this, so that all output from script.py
is sent to a single file.
import subprocess
with open('message.log', 'w') as stdout_file:
my_process = subprocess.Popen(["iPython.exe", "script.py"],
stdout=stdout_file,
stderr=subprocess.STDOUT)
However, subprocessing something which just calls iPython
to load another script is an awful way to work. Instead, you should just call the script.py
modules directly.
Upvotes: 1