youngminz
youngminz

Reputation: 1444

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

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?

Upvotes: 14

Views: 17283

Answers (3)

Eric Renouf
Eric Renouf

Reputation: 14520

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
$

Upvotes: 18

Ali SAID OMAR
Ali SAID OMAR

Reputation: 6792

BTW you can also control it:

import traceback
import sys



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

Upvotes: 8

Brian Cain
Brian Cain

Reputation: 966

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'

Upvotes: 7

Related Questions