Home > Net >  how can i redirect my error message from console to file in Python
how can i redirect my error message from console to file in Python

Time:02-11

i need to redirect my error message from console to file. for this example i need to insert message error into file:

"Traceback (most recent call last): File "C:/Users/", line 5, in 1/0 ZeroDivisionError: division by zero" .

i have already tried to do something like this.

from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    with redirect_stdout(f):
        1/0
        print('here is my error')

CodePudding user response:

You need to catch the error or your application will fail:

from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    try:
        1/0
    except ZeroDivisionError as e:
        f.write(e)

CodePudding user response:

If you plan to run your script in console itself, you can just use the bash's ">" operator to send the input of your command (in this situation : your script) in a file just like this :

python ./yourScript > ./outputFile

Everything that your script will print will go in the specified file.

  • Related