Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to write every warning in a .txt file in python?

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

like image 246
mazorin Avatar asked Nov 03 '25 06:11

mazorin


1 Answers

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.

like image 137
Arthur Tacca Avatar answered Nov 04 '25 19:11

Arthur Tacca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!