In C++, I can output to cout
and cerr
; in practice this results in code wherein I can redirect output to two files at once like:
./some_program > first_file.something 2> second_file.else
How would I accomplish this in python?
E.g. in Python 3, just import the equivalents of cout
and cerr
, namely sys.stdout
and sys.stderr
.
from sys import stdout, stderr
print('to standard output', file=stdout)
print('to standard error', file=stderr)
Then you can use your bash redirection as you normally would:
python program.py 1>output 2>errors
And if you want, you can even name them whatever you like. E.g.:
from sys import stdout as cout, stderr as cerr
print('to standard output', file=cout)
print('to standard error', file=cerr)
It's less "Pythonic," but if it helps you bridge the gap from your C++ experience, it may be a help.
If you want to redirect from the command line, it's pretty much the same way you would do in C++:
python file.py > first_file.txt 2> second_file.txt
Programmatically, you can do this with sys.stdout
and sys.stderr
, by monkey patching those with files of your choice.