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) + "]")
python类formatwarning()的实例源码
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 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 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 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)