0

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?

Chris
  • 28,822
  • 27
  • 83
  • 158

3 Answers3

2

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.

Jonathan Eunice
  • 21,653
  • 6
  • 75
  • 77
1

https://docs.python.org/3/library/sys.html

sys.stdout
sys.stderr

confused about stdin, stdout and stderr?

fernand0
  • 310
  • 1
  • 10
1

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.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139