我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用warnings.formatwarning()。
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 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 missing_units_warning(name, defaultunit): """ Warn if any unit is missing Parameters ---------- name: str name of the variable defaultunit: str default unit definition Raises ------ warning: warnings.warn warn if units are assumed """ warnings.formatwarning = warning_on_one_line msg = 'Variable {0:s} does not have explicit units. Assuming `{1:s}`\n' # stacklevel makes the correct code reference warnings.warn(msg.format(name, defaultunit), stacklevel=4)
def _showWarning(self, message, category, filename, lineno, file=None, line=None): # Don't display repeat warnings if str(message) in self.logged_warnings: return m = warnings.formatwarning(message, category, filename, lineno, line) self.log.warning(m) self.logged_warnings.add(str(message)) # Log this warning, but never display it to the user; it is # nearly un-actionable. if category == requestsexceptions.InsecurePlatformWarning: return if category == requestsexceptions.SNIMissingWarning: return # Disable InsecureRequestWarning when certificate validation is disabled if not self.config.verify_ssl: if category == requestsexceptions.InsecureRequestWarning: return self.error_queue.put(('Warning', m)) os.write(self.error_pipe, six.b('error\n'))
def play_note(self,note_name,note_duration): """Plays a single note by creating a 1 note song in song 0 """ current_song = 0 play_list=[] noError = True if noError: #Need to map ascii to numbers from the dict. if note_name in self.config.data['midi table']: play_list.append(self.config.data['midi table'][note_name]) play_list.append(note_duration) else: # That note doesn't exist. Plays nothing # Raise an error so the software knows that the input was bad play_list.append(self.config.data['midi table'][0]) warnings.formatwarning = custom_format_warning warnings.warn("Warning: Note '" + note_name + "' was not found in midi table") #create a song from play_list and play it self.create_song(current_song,play_list) self.play(current_song)
def _showwarning(message, category, filename, lineno, file=None, line=None): if file is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: _warning_logger.warning(warnings.formatwarning(message, category, filename, lineno, line).rstrip('\n'))
def customwarn(message, category, filename, lineno, *args, **kwargs): """Use the psyplot.warning logger for categories being out of PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning function for all the others.""" if category is PsyPlotWarning: logger.warning(warnings.formatwarning( "\n%s" % message, category, filename, lineno)) elif category is PsyPlotCritical: logger.critical(warnings.formatwarning( "\n%s" % message, category, filename, lineno), exc_info=True) else: old_showwarning(message, category, filename, lineno, *args, **kwargs)
def warn_with_traceback(message, category, filename, lineno, line=None): """ copied from: http://stackoverflow.com/questions/22373927/get-traceback-of-warnings """ traceback.print_stack() log = sys.stderr log.write(warnings.formatwarning( message, category, filename, lineno, line))
def _showwarning(message, category, filename, lineno, file=None, line=None): 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) warnlog.warning(s)
def warning(): def _warnformat(msg, category, filename, lineno, file=None, line=None): return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, msg) default_warn_format = warnings.formatwarning try: warnings.formatwarning = _warnformat yield warnings.warn finally: warnings.formatwarning = default_warn_format # Descriptor protocol for creating an attribute that is bound to an # (arbitrarily nested) attribute accessible to the instance at runtime.
def idle_showwarning(message, category, filename, lineno, file=None, line=None): if file is None: file = warning_stream try: file.write(warnings.formatwarning(message, category, filename, lineno, line=line)) except IOError: pass ## file (probably __stderr__) is invalid, warning dropped.
def deprecated(self, msg, *args, **kw): filename, lineno, func = self.log_obj.findCaller() depr_msg = warnings.formatwarning( msg, DeprecationWarning, filename, lineno) self.log_obj.warning(depr_msg, *args, **kw)
def customwarn(message, category, filename, lineno, file=None, line=None): sys.stdout.write(warnings.formatwarning( message, category, filename, lineno))
def customwarn(message, category, filename, lineno, file=None, line=None): #sys.stdout.write(warnings.formatwarning(message, category, filename, lineno)) log.warning(str(category.__name__) + ": " + str(message) + " [file:" + str(filename) + ", line:" + str(lineno) + "]")
def deprecated(): warnings.formatwarning = Warning.warning_on_one_line warnings.simplefilter("default") warnings.warn("pynit.Preprocess() will be deprecated soon. Please use pynit.Process() instead.", DeprecationWarning, stacklevel=2) warnings.simplefilter("ignore")
def __call__(self): """Run all check_* methods.""" if self.on: oldformatwarning = warnings.formatwarning warnings.formatwarning = self.formatwarning try: for name in dir(self): if name.startswith('check_'): method = getattr(self, name) if method and hasattr(method, '__call__'): method() finally: warnings.formatwarning = oldformatwarning
def formatwarning(self, message, category, filename, lineno, line=None): """Function to format a warning.""" return 'CherryPy Checker:\n%s\n\n' % message # This value should be set inside _cpconfig.
def warn_with_traceback(message, category, filename, lineno, file=None, line=None): traceback.print_stack() log = file if hasattr(file,'write') else sys.stderr log.write(warnings.formatwarning(message, category, filename, lineno, line))
def warn_with_traceback(message, category, filename, lineno, file=None, line=None): traceback.print_stack() log = file if hasattr(file, 'write') else sys.stderr log.write(warnings.formatwarning(message, category, filename, lineno, line))
def test_filteredOnceWarning(self): """ L{deprecate.warnAboutFunction} emits a warning that will be filtered once if L{warnings.filterwarning} is called with the module name of the deprecated function and an action of once. """ # Clean up anything *else* that might spuriously filter out the warning, # such as the "always" simplefilter set up by unittest._collectWarnings. # We'll also rely on trial to restore the original filters afterwards. del warnings.filters[:] warnings.filterwarnings( action="module", module="twisted_private_helper") from twisted_private_helper import module module.callTestFunction() module.callTestFunction() warningsShown = self.flushWarnings() self.assertEqual(len(warningsShown), 1) message = warningsShown[0]['message'] category = warningsShown[0]['category'] filename = warningsShown[0]['filename'] lineno = warningsShown[0]['lineno'] msg = warnings.formatwarning(message, category, filename, lineno) self.assertTrue( msg.endswith("module.py:9: DeprecationWarning: A Warning String\n" " return a\n"), "Unexpected warning string: %r" % (msg,))
def test_warningToFile(self): """ L{twisted.python.log.showwarning} passes warnings with an explicit file target on to the underlying Python warning system. """ message = "another unique message" category = FakeWarning filename = "warning-filename.py" lineno = 31 output = StringIO() log.showwarning(message, category, filename, lineno, file=output) self.assertEqual( output.getvalue(), warnings.formatwarning(message, category, filename, lineno)) # In Python 2.6 and higher, warnings.showwarning accepts # a "line" argument which gives the source line the warning # message is to include. line = "hello world" output = StringIO() log.showwarning(message, category, filename, lineno, file=output, line=line) self.assertEqual( output.getvalue(), warnings.formatwarning(message, category, filename, lineno, line))
def warn_with_traceback(message, category, filename, lineno, file=None, line=None): """Get full tracebacks when warning is raised by setting warnings.showwarning = warn_with_traceback See also -------- http://stackoverflow.com/questions/22373927/get-traceback-of-warnings """ import warnings import traceback traceback.print_stack() log = file if hasattr(file, 'write') else sys.stderr settings.write(warnings.formatwarning(message, category, filename, lineno, line))
def __call__(self): """Run all check_* methods.""" if self.on: oldformatwarning = warnings.formatwarning warnings.formatwarning = self.formatwarning try: for name in dir(self): if name.startswith("check_"): method = getattr(self, name) if method and hasattr(method, '__call__'): method() finally: warnings.formatwarning = oldformatwarning
def formatwarning(self, message, category, filename, lineno, line=None): """Function to format a warning.""" return "CherryPy Checker:\n%s\n\n" % message # This value should be set inside _cpconfig.
def show_warning_via_twisted( message, category, filename, lineno, file=None, line=None): """Replacement for `warnings.showwarning` that logs via Twisted.""" if file is None: # Try to find a module name with which to log this warning. module = get_module_for_file(filename) logger = twistedModern.Logger( "global" if module is None else module.__name__) # `message` is/can be an instance of `category`, so stringify. logger.warn( "{category}: {message}", message=str(message), category=category.__qualname__, filename=filename, lineno=lineno, line=line) else: # It's not clear why and when `file` will be specified, but try to # honour the intention. warning = warnings.formatwarning( message, category, filename, lineno, line) try: file.write(warning) file.flush() except OSError: pass # We tried. # Those levels for which we should emit log events.
def digit_led_ascii(self, display_string): """This command controls the four 7 segment displays using ASCII character codes. Arguments: display_string: A four character string to be displayed. This must be four characters. Any blank characters should be represented with a space: ' ' Due to the limited display, there is no control over upper or lowercase letters. create2api will automatically convert all chars to uppercase, but some letters (Such as 'B' and 'D') will still display as lowercase on the Create 2's display. C'est la vie. """ noError = True display_string = display_string.upper() if len(display_string) == 4: display_list = [] else: #Too many or too few characters! noError = False raise _ROIDataByteError("Invalid ASCII input (Must be EXACTLY four characters)") if noError: #Need to map ascii to numbers from the dict. for i in range (0,4): #Check that the character is in the list, if it is, add it. if display_string[i] in self.config.data['ascii table']: display_list.append(self.config.data['ascii table'][display_string[i]]) else: # Char was not available. Just print a blank space # Raise an error so the software knows that the input was bad display_list.append(self.config.data['ascii table'][' ']) warnings.formatwarning = custom_format_warning warnings.warn("Warning: Char '" + display_string[i] + "' was not found in ascii table") self.SCI.send(self.config.data['opcodes']['digit_led_ascii'], tuple(display_list)) else: raise _ROIFailedToSendError("Invalid data, failed to send") #NOTE ABOUT SONGS: For some reason you cannot play a new song immediately #after playing a different one, only the first song will play. You have to #time.sleep() at least a fraction of a second for the speaker to process
def play_song(self,song_number,note_string): """ Creates and plays a new song based off a string of notes and durations. note_string - a string of notes,durations for example: 'G5,16,G3,16,A#4,30' """ #splits the string of notes and durations into two lists split_list= note_string.split(',') note_list = split_list[0::2] duration_list = split_list[1::2] #creates a list for serial codes play_list = [] #convert the durations to integers duration_list = map(int, duration_list) noError = True if noError: #Need to map midi to numbers from the dict. for i in range (0,len(note_list)): #Check that the note is in the list, if it is, add it. if note_list[i] in self.config.data['midi table']: play_list.append(self.config.data['midi table'][note_list[i]]) play_list.append(duration_list[i]) else: # Note was not available. Play a rest # Raise an error so the software knows that the input was bad play_list.append(self.config.data['midi table']['rest']) play_list.append(duration_list[i]) warnings.formatwarning = custom_format_warning warnings.warn("Warning: Note '" + note_string + "' was not found in midi table") #play the song self.create_song(song_number,play_list) self.play(song_number) else: raise _ROIFailedToSendError("Invalid data, failed to send")
def main(): # Trigger cleanup on SIGTERM and SIGHUP signal(SIGTERM, exit_handler) signal(SIGHUP, exit_handler) cli_plugins = lago.plugins.load_plugins( lago.plugins.PLUGIN_ENTRY_POINTS['cli'] ) out_plugins = lago.plugins.load_plugins( lago.plugins.PLUGIN_ENTRY_POINTS['out'] ) parser = create_parser( cli_plugins=cli_plugins, out_plugins=out_plugins, ) args = parser.parse_args() config.update_args(args) logging.basicConfig(level=logging.DEBUG) logging.root.handlers = [ log_utils.TaskHandler( task_tree_depth=args.logdepth, level=getattr(logging, args.loglevel.upper()), dump_level=logging.ERROR, formatter=log_utils.ColorFormatter(fmt='%(msg)s', ) ) ] logging.captureWarnings(True) if args.ignore_warnings: logging.getLogger('py.warnings').setLevel(logging.ERROR) else: warnings.formatwarning = lambda message, *args, **kwargs: message args.out_format = out_plugins[args.out_format] if args.prefix_path: warnings.warn( 'The option --prefix-path is going to be deprecated, use ' '--workdir and --prefix instead', DeprecationWarning, ) try: cli_plugins[args.verb].do_run(args) except utils.LagoException as e: LOGGER.info(e.message) LOGGER.debug(e) sys.exit(2) except Exception: LOGGER.exception('Error occured, aborting') sys.exit(1)