Search code examples
pythonlinuxstdoutstderr

Which is better way to write out and err of python


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.


Solution

  • 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.