diff a/Doc/library/warnings.rst b/Doc/library/warnings.rst --- a/Doc/library/warnings.rst +++ b/Doc/library/warnings.rst @@ -388,3 +388,21 @@ .. versionadded:: 2.6 +Pre-built option +---------------- + +.. data:: option + + Pre-built :class:`optparse.Option` instance providing the same + functions as the :option:`-W` interpreter flag. Useful when + building tools related to running Python code such as a web + framework's development framework or a pluggable system, in order + to let users of the tool manipulate warnings without having to + explicitly call the Python interpreter. + + .. note:: + + In restricted environments where :mod:`optparse` is not + available, :data:`option` is set to `None`. + + .. versionadded:: 2.7 diff a/Lib/warnings.py b/Lib/warnings.py --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -8,7 +8,7 @@ import types __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", - "resetwarnings", "catch_warnings"] + "resetwarnings", "catch_warnings", "option"] def warnpy3k(message, category=None, stacklevel=1): @@ -397,3 +397,14 @@ bytes_action = "ignore" simplefilter(bytes_action, category=BytesWarning, append=1) del _warnings_defaults + +# optparse option to control warnings settings +option = None +try: + import optparse + option = optparse.Option( + '-W', action="callback", type=str, metavar='arg', + help='warning control; arg is action:message:category:module:lineno', + callback=lambda caller, option, value, parser: _setoption(value)) +except ImportError: + pass