concern
You want your program to generate warning messages (such as deprecated features or usage issues).
prescription
To output a warning message, use the()
function. Example:
import warnings def func(x, y, logfile=None, debug=False): if logfile is not None: ('logfile argument deprecated', DeprecationWarning) ...
warn()
The parameters are a warning message and a warning class of one of the following types: UserWarning, DeprecationWarning, SyntaxWarning, RuntimeWarning, ResourceWarning, or FutureWarning.
The handling of warnings depends on how you run the interpreter and some other configurations. For example, if you use-W all
option to run Python, you will get the following output:
bash % python3 -W all
:5: DeprecationWarning: logfile argument is deprecated
('logfile argument is deprecated', DeprecationWarning)
Typically, warnings are output as standard errors. If you want to convert a warning to an exception, you can use the-W error
Options:
bash % python3 -W error
Traceback (most recent call last):
File "", line 10, in <module>
func(2, 3, logfile='')
File "", line 5, in func
('logfile argument is deprecated', DeprecationWarning)
DeprecationWarning: logfile argument is deprecated
bash %
talk over
Outputting warning messages can be useful when you are maintaining software that prompts the user for certain information, but doesn't need to raise it to the exception level. For example, assuming you're going to change the functionality of a library or framework, you can start by outputting a warning message for the part you're going to change, along with a period of backward compatibility. You could also warn the user about some problematic uses of the code.
As another example of warning usage of the built-in library, the following demonstrates a warning message generated when a file is destroyed without closing it:
>>> import warnings >>> ('always') >>> f = open('/etc/passwd') >>> del f __main__:1: ResourceWarning: unclosed file <_io.TextIOWrapper name='/etc/passwd' mode='r' encoding='UTF-8'> >>>
By default, not all warning messages appear. The -W option controls the output of warning messages. -W all outputs all warning messages, -W ignore ignores all warnings, and -W error converts warnings to exceptions. Alternatively, you can use the()
function controls the output. The always argument causes all warning messages to appear, `ignore ignores all warnings, and error converts warnings into exceptions.
This is sufficient for the simple case of generating warning messages. The warnings module provides a number of more advanced configuration options for filtering and warning message handling. For more information, see thePython Documentation
This is the detailed content of how to output warning messages in Python, for more information about Python output warning messages, please pay attention to my other related articles!