1

I need to redirect my error message from the console to a file. For this example, I need to insert the error message into a file:

Traceback (most recent call last):
  File "C:/Users/", line 5, in <module>
    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')
Dave Yarwood
  • 2,866
  • 1
  • 17
  • 29
nc1318
  • 19
  • 2

3 Answers3

1

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.

Krigan
  • 31
  • 9
  • You have verified that this captures error messages? And what if `bash` is not being used? – Scott Hunter Feb 10 '22 at 13:44
  • Because Python (like most other programming languages) prints error messages to stderr, this solution would not work. `python script.py 2> errors.txt` would work. `2>` is the syntax (at least in Bash) to redirect stderr into another file/process. – Dave Yarwood Feb 12 '22 at 20:55
  • 1
    ...although, actually, looking at the question again: the program _does_ explicitly print exceptions to stdout, so this solution actually would work! – Dave Yarwood Feb 12 '22 at 20:56
  • @DaveYarwood: It has a `print` statement, which never gets reached, and redirects stdout to a file. How does this "explicitly print exceptions to stdout"? – Scott Hunter Feb 13 '22 at 12:44
1

Note: This assumes you're using Bash. I see that you are using Windows, so it's likely that you aren't using Bash. But from what I've read, this should still be applicable if you are using Cmd.exe, it's just that the syntax might be slightly different.

I think it's better to handle error message output outside of your script. Your script should attempt to do the "happy path" work and print an error to stderr if something goes wrong. This is what should happen by default in every programming language. Python gets this right.

Here is an example script:

print("Dividing by 0 now, I sure hope this works!")

1/0

print("Holy cow, it worked!")

If I run this script, the first line prints to stdout, and then the ZeroDivisionError output prints to stderr:

$ python /tmp/script.py 
Dividing by 0 now, I sure hope this works!
Traceback (most recent call last):
  File "/tmp/script.py", line 3, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

If I want to run the script and collect any error output in a file, I can use redirection in my shell when I run the command:

$ python /tmp/script.py 2> /tmp/errors.txt
Dividing by 0 now, I sure hope this works!

$ cat /tmp/errors.txt 
Traceback (most recent call last):
  File "/tmp/script.py", line 3, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero
Dave Yarwood
  • 2,866
  • 1
  • 17
  • 29
0

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)
Filipe S.
  • 74
  • 5
  • So every potential error needs to be wrapped it its own `try` block? And OP said nothing about preventing the error from stopping the program. – Scott Hunter Feb 10 '22 at 13:27
  • How else are you going to scale an application if you don't cover all potential errors? – Filipe S. Feb 10 '22 at 13:28
  • Not relevant to this particular question. – Scott Hunter Feb 10 '22 at 13:31
  • Filipe, I think this could be a great solution depending on the OP's needs, who are we to determine his needs? Let's see what he says. And you can always `raise` the error after writing if you need. – Eli Harold Feb 10 '22 at 13:34
  • 1
    You could also use `try:` `#all code here` `except Exception as e:` `f.write(e)` `raise e`. That would make the file basically an error log and not effect how the file runs. If you want an error-log effect you can just append the file instead of writing over it. – Eli Harold Feb 10 '22 at 13:45
  • @EliHarold: You should put that in a comment on the question and/or as its own answer. – Scott Hunter Feb 10 '22 at 13:51
  • @ScottHunter My comment is a suggested amendment to this answer, why would I make it a new incomplete answer? Also the comment would not make much sense by itself, but you are welcome to copy and paste it anywhere that you think it should be. You even have my permission to post it as an answer if you believe it should be one. – Eli Harold Feb 10 '22 at 14:12
  • can i redirect error msg from console to file without try except? @Filipe S. – nc1318 Feb 11 '22 at 08:44
  • i don't neet to use block try/except. i need just to redirect error msg. is it possible? – nc1318 Feb 11 '22 at 08:57