本文整理汇总了Python中warnings.filters方法的典型用法代码示例。如果您正苦于以下问题:Python warnings.filters方法的具体用法?Python warnings.filters怎么用?Python warnings.filters使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类warnings
的用法示例。
在下文中一共展示了warnings.filters方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: filter
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def filter(self, category=Warning, message="", module=None):
"""
Add a new suppressing filter or apply it if the state is entered.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expression matching the warning message.
module : module, optional
Module to filter for. Note that the module (and its file)
must match exactly and cannot be a submodule. This may make
it unreliable for external modules.
Notes
-----
When added within a context, filters are only added inside
the context and will be forgotten when the context is exited.
"""
self._filter(category=category, message=message, module=module,
record=False)
示例2: filter
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def filter(self, category=Warning, message="", module=None):
"""
Add a new suppressing filter or apply it if the state is entered.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expression matching the warning message.
module : module, optional
Module to filter for. Note that the module (and its file)
must match exactly and cannot be a submodule. This may make
it unreliable for external modules.
Notes
-----
When added within a context, filters are only added inside
the context and will be forgotten when the context is exited.
"""
self._filter(category=category, message=message, module=module,
record=False)
示例3: __enter__
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def __enter__(self):
if self._entered:
raise RuntimeError("Cannot enter %r twice" % self)
self._entered = True
self._filters = self._module.filters
self._module.filters = self._filters[:]
self._showwarning = self._module.showwarning
if self._record:
log = []
def showwarning(*args, **kwargs):
log.append(WarningMessage(*args, **kwargs))
self._module.showwarning = showwarning
return log
else:
return None
示例4: runsource
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def runsource(self, source):
"Extend base class method: Stuff the source in the line cache first"
filename = self.stuffsource(source)
self.more = 0
self.save_warnings_filters = warnings.filters[:]
warnings.filterwarnings(action="error", category=SyntaxWarning)
if isinstance(source, types.UnicodeType):
from idlelib import IOBinding
try:
source = source.encode(IOBinding.encoding)
except UnicodeError:
self.tkconsole.resetoutput()
self.write("Unsupported characters in input\n")
return
try:
# InteractiveInterpreter.runsource() calls its runcode() method,
# which is overridden (see below)
return InteractiveInterpreter.runsource(self, source, filename)
finally:
if self.save_warnings_filters is not None:
warnings.filters[:] = self.save_warnings_filters
self.save_warnings_filters = None
示例5: test_warn_wrong_warning
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def test_warn_wrong_warning(self):
def f():
warnings.warn("yo", DeprecationWarning)
failed = False
filters = sys.modules['warnings'].filters[:]
try:
try:
# Should raise an AssertionError
assert_warns(UserWarning, f)
failed = True
except AssertionError:
pass
finally:
sys.modules['warnings'].filters = filters
if failed:
raise AssertionError("wrong warning caught by assert_warn")
# Tests for docstrings:
示例6: runWithWarningsSuppressed
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def runWithWarningsSuppressed(suppressedWarnings, f, *a, **kw):
"""Run the function C{f}, but with some warnings suppressed.
@param suppressedWarnings: A list of arguments to pass to filterwarnings.
Must be a sequence of 2-tuples (args, kwargs).
@param f: A callable, followed by its arguments and keyword arguments
"""
for args, kwargs in suppressedWarnings:
warnings.filterwarnings(*args, **kwargs)
addedFilters = warnings.filters[:len(suppressedWarnings)]
try:
result = f(*a, **kw)
except:
exc_info = sys.exc_info()
_resetWarningFilters(None, addedFilters)
reraise(exc_info[1], exc_info[2])
else:
if isinstance(result, defer.Deferred):
result.addBoth(_resetWarningFilters, addedFilters)
else:
_resetWarningFilters(None, addedFilters)
return result
示例7: test_flushedWarningsConfiguredAsErrors
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def test_flushedWarningsConfiguredAsErrors(self):
"""
If a warnings filter has been installed which turns warnings into
exceptions, tests which emit those warnings but flush them do not have
an error added to the reporter.
"""
class CustomWarning(Warning):
pass
result = TestResult()
case = Mask.MockTests('test_flushed')
case.category = CustomWarning
originalWarnings = warnings.filters[:]
try:
warnings.simplefilter('error')
case.run(result)
self.assertEqual(result.errors, [])
finally:
warnings.filters[:] = originalWarnings
示例8: runsource
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def runsource(self, source):
"Extend base class method: Stuff the source in the line cache first"
filename = self.stuffsource(source)
self.more = 0
self.save_warnings_filters = warnings.filters[:]
warnings.filterwarnings(action="error", category=SyntaxWarning)
# at the moment, InteractiveInterpreter expects str
assert isinstance(source, str)
#if isinstance(source, str):
# from idlelib import IOBinding
# try:
# source = source.encode(IOBinding.encoding)
# except UnicodeError:
# self.tkconsole.resetoutput()
# self.write("Unsupported characters in input\n")
# return
try:
# InteractiveInterpreter.runsource() calls its runcode() method,
# which is overridden (see below)
return InteractiveInterpreter.runsource(self, source, filename)
finally:
if self.save_warnings_filters is not None:
warnings.filters[:] = self.save_warnings_filters
self.save_warnings_filters = None
示例9: get_warnings_filters
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def get_warnings_filters(self):
return id(warnings.filters), warnings.filters, warnings.filters[:]
示例10: restore_warnings_filters
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def restore_warnings_filters(self, saved_filters):
warnings.filters = saved_filters[1]
warnings.filters[:] = saved_filters[2]
示例11: __enter__
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def __enter__(self):
warnings.simplefilter('error')
self.added = warnings.filters[0]
示例12: __exit__
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def __exit__(self, exc, value, tb):
if warnings.filters[0] != self.added:
raise RuntimeError('Somone has done something to the filters')
warnings.filters.pop(0)
return False # allow any exceptions to propagate
示例13: _clear_registries
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def _clear_registries(self):
if hasattr(warnings, "_filters_mutated"):
# clearing the registry should not be necessary on new pythons,
# instead the filters should be mutated.
warnings._filters_mutated()
return
# Simply clear the registry, this should normally be harmless,
# note that on new pythons it would be invalidated anyway.
for module in self._tmp_modules:
if hasattr(module, "__warningregistry__"):
module.__warningregistry__.clear()
示例14: record
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def record(self, category=Warning, message="", module=None):
"""
Append a new recording filter or apply it if the state is entered.
All warnings matching will be appended to the ``log`` attribute.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expression matching the warning message.
module : module, optional
Module to filter for. Note that the module (and its file)
must match exactly and cannot be a submodule. This may make
it unreliable for external modules.
Returns
-------
log : list
A list which will be filled with all matched warnings.
Notes
-----
When added within a context, filters are only added inside
the context and will be forgotten when the context is exited.
"""
return self._filter(category=category, message=message, module=module,
record=True)
示例15: __enter__
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import filters [as 别名]
def __enter__(self):
if self._entered:
raise RuntimeError("cannot enter suppress_warnings twice.")
self._orig_show = warnings.showwarning
self._filters = warnings.filters
warnings.filters = self._filters[:]
self._entered = True
self._tmp_suppressions = []
self._tmp_modules = set()
self._forwarded = set()
self.log = [] # reset global log (no need to keep same list)
for cat, mess, _, mod, log in self._suppressions:
if log is not None:
del log[:] # clear the log
if mod is None:
warnings.filterwarnings(
"always", category=cat, message=mess)
else:
module_regex = mod.__name__.replace('.', r'\.') + '$'
warnings.filterwarnings(
"always", category=cat, message=mess,
module=module_regex)
self._tmp_modules.add(mod)
warnings.showwarning = self._showwarning
self._clear_registries()
return self