3

I would like my program to write every warning in a .txt file. Is there any way to do this without using catch_warnings?

9
  • Yes it is possible. Open/create a file and then write to it.
    – Terry
    Jul 16, 2020 at 9:47
  • 2
    @Terry That seems pretty unrelated to Python warnings. Jul 16, 2020 at 9:53
  • I added the "compiler-warnings" tag. Although Python obviously doesn't have a compiler, its built-in warnings are basically analgous to compiler warnings in other langauges, so it seemed most appropriate. Jul 16, 2020 at 9:54
  • 1
    @Tomerikoo They are talking about Python warnings which are different from exceptions. Jul 16, 2020 at 10:06
  • @ArthurTacca oh I see. That was not very clear from the question (I am not familiar with that module...). Thanks. In that case it seems your answer solves this
    – Tomerikoo
    Jul 16, 2020 at 10:09

1 Answer 1

6

One option is to use the built-in Python logging. There is a lot of information on the internet about how to use the Python logging system, especially in the Python documentation for it (e.g. see the Logging HOWTO). But the simplest way to turn on logging to a file is with the basicConfig() function, like this:

import logging
logging.basicConfig(filename="myfile.txt",level=logging.DEBUG)

Now you can enable logging of warnings with the captureWarnings() function:

logging.captureWarnings(True)

As a bonus, you can now also log your own messages:

logging.info("My own message")

An alternative is to replace the warning handler yourself. This is slightly more work but it is a bit more focused on just warnings. The warning module documentation for showwarning() says:

You may replace this function with any callable by assigning to warnings.showwarning.

So you could define your own function with the same parameter list, and assign it to that variable:

warning_file = open("warnings.txt", "w")

def mywarning(message, category, filename, lineno, file=None, line=None):
    warning_file.write(warnings.formatwarning(message, category, filename, lineno, file, line))

warnings.showwarning = mywarning

Note that I've opened warning_file outside the function so it will be opened once when your Python script starts. I also used the formatwarning() function so that the output is the same format as the warnings module usually outputs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.