2

I am writing python in Linux. I want to write the python output and error into different files than output them on the console.

Say if I have this python file example.py:

print('console output')
print(1/0)

I tried different way.
1. By executing the following command
python example.py >output 2>log
2. Update the example.py

logf = open("./log", "w")
try:
    print('console output')
    print(1/0)
except Exception as e:
    logf.write(str(e)) 

and execute python example.py >output

The logs are different. 1st method:

Traceback (most recent call last):
  File "try.py", line 2, in <module>
    print(1/0)
ZeroDivisionError: division by zero

and for 2nd method:

division by zero

So I want to ask:

  1. why two logs are different? And how to make the 2nd output same as 1st one.
  2. Which is better way of write error into files? Or there is a better way of doing this.

Thanks for helping with my questions.

Echan
  • 1,395
  • 14
  • 15
  • 1
    For your first question, it sounds like you're asking how to output a traceback instead of just the error message - does [this post](https://stackoverflow.com/questions/3702675/how-to-print-the-full-traceback-without-halting-the-program) help? – Random Davis Nov 09 '18 at 17:09

2 Answers2

2

Leave the script the simple, original way:

# example.py
print('console output')
print(1/0)

Use easy trick in shell:

$ python example.py &> log.txt

If you wanted some other custom behaviour on unhandled exceptions, set a sys.excepthook.

wim
  • 338,267
  • 99
  • 616
  • 750
0

To combine both stdout and stderr into one file, which is also helpful when using more (or less) command

python example.py 2>&1 > output
python example.py 2>&1 | more

To make each go into separate files

python example.py 2> error > output

To ignore stederr

python example 2>/dev/null

Hope this helps.

dlink
  • 1,489
  • 17
  • 22