牛骨文教育服务平台(让学习变的简单)

问题

You want to have your program issue warning messages (e.g., about deprecated featuresor usage problems).

解决方案

To have your program issue a warning message, use the warnings.warn() function. Forexample:

import warnings

def func(x, y, logfile=None, debug=False):if logfile is not None:warnings.warn(‘logfile argument deprecated", DeprecationWarning)
...

The arguments to warn() are a warning message along with a warning class, which istypically one of the following: UserWarning, DeprecationWarning, SyntaxWarning,RuntimeWarning, ResourceWarning, or FutureWarning.The handling of warnings depends on how you have executed the interpreter and otherconfiguration. For example, if you run Python with the -W all option, you’ll get outputsuch as the following:

bash % python3 -W all example.pyexample.py:5: DeprecationWarning: logfile argument is deprecated

warnings.warn(‘logfile argument is deprecated", DeprecationWarning)

Normally, warnings just produce output messages on standard error. If you want to turnwarnings into exceptions, use the -W error option:

bash % python3 -W error example.pyTraceback (most recent call last):

File “example.py”, line 10, in func(2, 3, logfile="log.txt")File “example.py”, line 5, in funcwarnings.warn(‘logfile argument is deprecated", DeprecationWarning)

DeprecationWarning: logfile argument is deprecatedbash %

讨论

Issuing a warning message is often a useful technique for maintaining software andassisting users with issues that don’t necessarily rise to the level of being a full-fledgedexception. For example, if you’re going to change the behavior of a library or framework,you can start issuing warning messages for the parts that you’re going to change whilestill providing backward compatibility for a time. You can also warn users about prob‐lematic usage issues in their code.As another example of a warning in the built-in library, here is an example of a warningmessage generated by destroying a file without closing it:

>>> import warnings
>>> warnings.simplefilter("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 to Python can control theoutput of warning messages. -W all will output all warning messages, -W ignoreignores all warnings, and -W error turns warnings into exceptions. As an alternative,you can can use the warnings.simplefilter() function to control output, as justshown. An argument of always makes all warning messages appear, ignore ignores allwarnings, and error turns warnings into exceptions.For simple cases, this is all you really need to issue warning messages. The warningsmodule provides a variety of more advanced configuration options related to the fil‐tering and handling of warning messages. See the Python documentation for moreinformation.