我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用warnings.showwarning()。
def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s)
def catch_warnings(): """Catch warnings in a with block in a list""" # make sure deprecation warnings are active in tests warnings.simplefilter('default', category=DeprecationWarning) filters = warnings.filters warnings.filters = filters[:] old_showwarning = warnings.showwarning log = [] def showwarning(message, category, filename, lineno, file=None, line=None): log.append(locals()) try: warnings.showwarning = showwarning yield log finally: warnings.filters = filters warnings.showwarning = old_showwarning
def execute(self): def showwarning(message, category, filename, fileno, file=None, line=None): msg = warnings.formatwarning(message, category, filename, fileno, line) self.log.warning(msg.strip()) with warnings.catch_warnings(): warnings.simplefilter("always") warnings.showwarning = showwarning try: return self.run() except SystemExit: raise except: self.log.critical(traceback.format_exc().strip()) sys.exit(1)
def startLoggingWithObserver(observer, setStdout=1): """Initialize logging to a specified observer. If setStdout is true (defaults to yes), also redirect sys.stdout and sys.stderr to the specified file. """ global defaultObserver, _oldshowwarning if not _oldshowwarning: _oldshowwarning = warnings.showwarning warnings.showwarning = showwarning if defaultObserver: defaultObserver.stop() defaultObserver = None addObserver(observer) msg("Log opened.") if setStdout: sys.stdout = logfile sys.stderr = logerr
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
def interact(self): while 1: try: # catches EOFError's and KeyboardInterrupts during execution try: # catches KeyboardInterrupts during editing try: # warning saver # can't have warnings spewed onto terminal sv = warnings.showwarning warnings.showwarning = eat_it l = unicode(self.reader.readline(), 'utf-8') finally: warnings.showwarning = sv except KeyboardInterrupt: print("KeyboardInterrupt") else: if l: self.execute(l) except EOFError: break except KeyboardInterrupt: continue
def test_warnings(self): with warnings.catch_warnings(): logging.captureWarnings(True) try: warnings.filterwarnings("always", category=UserWarning) file = io.StringIO() h = logging.StreamHandler(file) logger = logging.getLogger("py.warnings") logger.addHandler(h) warnings.warn("I'm warning you...") logger.removeHandler(h) s = file.getvalue() h.close() self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0) #See if an explicit file uses the original implementation file = io.StringIO() warnings.showwarning("Explicit", UserWarning, "dummy.py", 42, file, "Dummy line") s = file.getvalue() file.close() self.assertEqual(s, "dummy.py:42: UserWarning: Explicit\n Dummy line\n") finally: logging.captureWarnings(False)
def test_warnings(self): with warnings.catch_warnings(): logging.captureWarnings(True) try: warnings.filterwarnings("always", category=UserWarning) file = cStringIO.StringIO() h = logging.StreamHandler(file) logger = logging.getLogger("py.warnings") logger.addHandler(h) warnings.warn("I'm warning you...") logger.removeHandler(h) s = file.getvalue() h.close() self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0) #See if an explicit file uses the original implementation file = cStringIO.StringIO() warnings.showwarning("Explicit", UserWarning, "dummy.py", 42, file, "Dummy line") s = file.getvalue() file.close() self.assertEqual(s, "dummy.py:42: UserWarning: Explicit\n Dummy line\n") finally: logging.captureWarnings(False)
def idle_showwarning( message, category, filename, lineno, file=None, line=None): """Show Idle-format warning (after replacing warnings.showwarning). The differences are the formatter called, the file=None replacement, which can be None, the capture of the consequence AttributeError, and the output of a hard-coded prompt. """ if file is None: file = warning_stream try: file.write(idle_formatwarning( message, category, filename, lineno, line=line)) file.write(">>> ") except (AttributeError, IOError): pass # if file (probably __stderr__) is invalid, skip warning.
def test_warnings(self): with warnings.catch_warnings(): logging.captureWarnings(True) self.addCleanup(logging.captureWarnings, False) warnings.filterwarnings("always", category=UserWarning) stream = io.StringIO() h = logging.StreamHandler(stream) logger = logging.getLogger("py.warnings") logger.addHandler(h) warnings.warn("I'm warning you...") logger.removeHandler(h) s = stream.getvalue() h.close() self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0) #See if an explicit file uses the original implementation a_file = io.StringIO() warnings.showwarning("Explicit", UserWarning, "dummy.py", 42, a_file, "Dummy line") s = a_file.getvalue() a_file.close() self.assertEqual(s, "dummy.py:42: UserWarning: Explicit\n Dummy line\n")
def _initialize(): import warnings # filter out some harmless warnings about SciPy's CSR matrix format. warnings.filterwarnings('ignore', message='.*', module='scipy\.sparse\.compressed.*', lineno=122) # Format warnings nicely def _showwarning(message, category, filename, lineno, line=None): import sys warning = category.__name__ print >> sys.stderr print >> sys.stderr, '>> {}: {}'.format(warning, message) print >> sys.stderr warnings.showwarning = _showwarning
def interact(self): while 1: try: # catches EOFError's and KeyboardInterrupts during execution try: # catches KeyboardInterrupts during editing try: # warning saver # can't have warnings spewed onto terminal sv = warnings.showwarning warnings.showwarning = eat_it l = unicode(self.reader.readline(), 'utf-8') finally: warnings.showwarning = sv except KeyboardInterrupt: print "KeyboardInterrupt" else: if l: self.execute(l) except EOFError: break except KeyboardInterrupt: continue
def test_warnings(self): with warnings.catch_warnings(): logging.captureWarnings(True) self.addCleanup(logging.captureWarnings, False) warnings.filterwarnings("always", category=UserWarning) stream = io.StringIO() h = logging.StreamHandler(stream) logger = logging.getLogger("py.warnings") logger.addHandler(h) warnings.warn("I'm warning you...") logger.removeHandler(h) s = stream.getvalue() h.close() self.assertGreater(s.find("UserWarning: I'm warning you...\n"), 0) #See if an explicit file uses the original implementation a_file = io.StringIO() warnings.showwarning("Explicit", UserWarning, "dummy.py", 42, a_file, "Dummy line") s = a_file.getvalue() a_file.close() self.assertEqual(s, "dummy.py:42: UserWarning: Explicit\n Dummy line\n")