Does Python traceback.print_exc() prints to stdout or stderr?

10,166

Solution 1

It prints to stderr, as can be seen from the following test:

$ cat test.py
try:
    raise IOError()
except:
    import traceback
    traceback.print_exc()
$ python test.py
Traceback (most recent call last):
  File "test.py", line 2, in <module>
     raise IOError()
IOError
$ python test.py > /dev/null
Traceback (most recent call last):
  File "test.py", line 2, in <module>
     raise IOError()
IOError
$ python test.py 2> /dev/null
$

Solution 2

BTW you can also control it:

import traceback
import sys



try:
    raise Exception
except Exception as E:
    traceback.print_exc(file=sys.stderr)

Solution 3

According to the python documentation states "If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output." This means you can control how / where the output is printed.

with open(outFile) as fp
    print_exc(fp)

The above example will print to the file 'outFile'

Share:
10,166
youngminz
Author by

youngminz

Updated on June 07, 2022

Comments

  • youngminz
    youngminz almost 2 years

    I've read some Python docs, but I can't find where the print_exc function prints. So I searched some stack overflow, it says "print_exc() prints formatted exception to stdout". Link

    I've been so confused.. In my opinion, that function should print to stderr because it's ERROR!.. What is right?