There are different standard ways to do this (On all computing clusters I know, there is at least an option to do it automatically).
Let me point out a few which should suffice your needs:
If you start your program from a Linux console, it's very easy:
you can use the
>
at the and of any command to redirect all standard output (which usually get's printed on your terminal otherwise.
If you use
&>
, both the standarad output and standard error get redirected, such that you also get tracebacks and error messages.
Examples:
Code: Select all
python my_script.py > file_where_stdout_appears.txt # here, error messages still get printed to your terminal
python my_script.py &> file_for stdout_and_stderr.txt # here, both output and error messages get redirected to the file
python my_script.py > file_for_stdout.txt 2> file_for_stderr.txt # redirect error message to different file
If you've never learned this, take for example a look at
this (old) website. This
cheatsheet is also very nice.
Of course, you might be bound (or just more used) to Windows...
In that case, I'd suggest to simply use the build-in ways provided by python itself
Take a look at
this page of the python documentation.
The relevant example is this one:
Code: Select all
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
Slightly adjusted to our needs:
Code: Select all
from contextlib import redirect_stdout
def my_function():
print("here, I could call tenpy models...")
print("this is still usual output")
with open('myoutput.txt', 'w') as f:
with redirect_stdout(f):
my_function()
print("and this is again usual output")
A drawback of this approach is that it seems to be more difficult to also capture error messages. (Although there is a
redirect_stderr
, it does not seem to redirect any python error messages...)