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:
Thanks for helping with my questions.
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
.