本文整理汇总了Python中sys.excepthook函数的典型用法代码示例。如果您正苦于以下问题:Python excepthook函数的具体用法?Python excepthook怎么用?Python excepthook使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了excepthook函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: check_http_signature
def check_http_signature(self, path, query):
try:
qargs = dict([b.split("=") for b in query.split("&")])
ts = qargs['ts']
sig = qargs['sig']
keyid = qargs.get("k", "default") # not used yet
if sig in self.replay:
print("replayed signature " + sig + " in request for " + path)
return False
its = int(ts) / 1000
now = time.time()
max = self.signature_max_age
print("request timestamp: " + ts + ", min: " + str(now - max) + ", max: " + str(now + max))
if (its < (now - max)) or (its > (now + max)):
return False
message = (path + "\n" + ts).encode()
check = siphash.SipHash_2_4(self.get_sign_key(keyid), message).hexdigest()
print("request signature: " + sig + ", expecting: " + check.decode())
if check == sig.encode():
self.replay.insert(0, sig)
self.replay = self.replay[:self.replay_memory]
return True
return False
except Exception as e:
sys.excepthook(*sys.exc_info())
return False
开发者ID:GNOME,项目名称:rhythmbox,代码行数:31,代码来源:webremote.py
示例2: emit_sound
def emit_sound(sounds, sound, outdir):
try:
i = sound.soundId
if swf.sound.supported(sound):
filename = 'sound-%d%s' % (i, swf.consts.AudioCodec.FileExtensions[sound.soundFormat])
with open(path.join(outdir, filename), 'wb') as sf:
swf.sound.write_sound_to_file(sound, sf)
sounds[i] = dict(status = 'extracted',
id = i,
kind = 'sound',
filesize = path.getsize(path.join(outdir, filename)),
mimetype = swf.consts.AudioCodec.MimeTypes[sound.soundFormat],
codec = swf.consts.AudioCodec.tostring(sound.soundFormat),
filename = filename,
**get_sound_meta(path.join(outdir, filename)))
elif swf.sound.junk(sound):
pass # discard junk
else:
sounds[i] = dict(status = 'skipped',
id = i,
kind = 'sound',
reason = swf.sound.reason_unsupported(sound),
codec = swf.consts.AudioCodec.tostring(sound.soundFormat))
except Exception:
print 'sound', i, 'extraction failed:'
sys.excepthook(*sys.exc_info())
开发者ID:ctz,项目名称:flashover,代码行数:26,代码来源:swfback.py
示例3: main
def main(listener_fd, alive_r, preload, main_path=None, sys_path=None):
'''Run forkserver.'''
if preload:
if '__main__' in preload and main_path is not None:
process.current_process()._inheriting = True
try:
spawn.import_main_path(main_path)
finally:
del process.current_process()._inheriting
for modname in preload:
try:
__import__(modname)
except ImportError:
pass
util._close_stdin()
# ignoring SIGCHLD means no need to reap zombie processes
# letting SIGINT through avoids KeyboardInterrupt tracebacks
handlers = {
signal.SIGCHLD: signal.SIG_IGN,
signal.SIGINT: signal.SIG_DFL,
}
old_handlers = {sig: signal.signal(sig, val)
for (sig, val) in handlers.items()}
with socket.socket(socket.AF_UNIX, fileno=listener_fd) as listener, \
selectors.DefaultSelector() as selector:
_forkserver._forkserver_address = listener.getsockname()
selector.register(listener, selectors.EVENT_READ)
selector.register(alive_r, selectors.EVENT_READ)
while True:
try:
while True:
rfds = [key.fileobj for (key, events) in selector.select()]
if rfds:
break
if alive_r in rfds:
# EOF because no more client processes left
assert os.read(alive_r, 1) == b''
raise SystemExit
assert listener in rfds
with listener.accept()[0] as s:
code = 1
if os.fork() == 0:
try:
_serve_one(s, listener, alive_r, old_handlers)
except Exception:
sys.excepthook(*sys.exc_info())
sys.stderr.flush()
finally:
os._exit(code)
except OSError as e:
if e.errno != errno.ECONNABORTED:
raise
开发者ID:uqfoundation,项目名称:multiprocess,代码行数:60,代码来源:forkserver.py
示例4: tst_lock_rm
def tst_lock_rm(self):
# Extract tar
tempdir = os.path.join(self.mnt_dir, 'lock_dir')
filename = os.path.join(tempdir, 'myfile')
os.mkdir(tempdir)
with open(filename, 'w') as fh:
fh.write('Hello, world')
# copy
try:
s3ql.lock.main([tempdir])
except:
sys.excepthook(*sys.exc_info())
pytest.fail("s3qllock raised exception")
# Try to delete
assert_raises(PermissionError, os.unlink, filename)
# Try to write
with pytest.raises(PermissionError):
open(filename, 'w+').write('Hello')
# delete properly
try:
s3ql.remove.main([tempdir])
except:
sys.excepthook(*sys.exc_info())
pytest.fail("s3qlrm raised exception")
assert 'lock_dir' not in llfuse.listdir(self.mnt_dir)
开发者ID:NickChen0113,项目名称:s3ql,代码行数:31,代码来源:t5_lock_rm.py
示例5: run_with_except_hook
def run_with_except_hook(*args, **kw):
try:
run_old(*args, **kw)
except (KeyboardInterrupt, SystemExit):
raise
except:
sys.excepthook(*sys.exc_info())
开发者ID:leovale,项目名称:ochDownloader,代码行数:7,代码来源:starter.py
示例6: threadMain
def threadMain(self):
better_exchook.install()
thread = currentThread()
setCurThreadName("PyMod %s" % self.name)
while True:
if self.module:
try:
reload(self.module)
except Exception:
print "couldn't reload module", self.module
sys.excepthook(*sys.exc_info())
# continue anyway, maybe it still works and maybe the mainFunc does sth good/important
else:
self.module = __import__(self.moduleName)
mainFunc = getattr(self.module, self.mainFuncName)
try:
mainFunc()
except KeyboardInterrupt:
break
except Exception:
print "Exception in module", self.name
sys.excepthook(*sys.exc_info())
if not thread.reload: break
sys.stdout.write("reloading module %s\n" % self.name)
thread.cancel = False
thread.reload = False
thread.waitQueue = None
开发者ID:BMXE,项目名称:music-player,代码行数:27,代码来源:utils.py
示例7: _exitfunc
def _exitfunc(cls):
# At shutdown invoke finalizers for which atexit is true.
# This is called once all other non-daemonic threads have been
# joined.
reenable_gc = False
try:
if cls._registry:
import gc
if gc.isenabled():
reenable_gc = True
gc.disable()
pending = None
while True:
if pending is None or finalize._dirty:
pending = cls._select_for_exit()
finalize._dirty = False
if not pending:
break
f = pending.pop()
try:
# gc is disabled, so (assuming no daemonic
# threads) the following is the only line in
# this function which might trigger creation
# of a new finalizer
f()
except Exception:
sys.excepthook(*sys.exc_info())
assert f not in cls._registry
finally:
# prevent any more finalizers from executing during shutdown
finalize._shutdown = True
if reenable_gc:
gc.enable()
开发者ID:gdementen,项目名称:numba,代码行数:33,代码来源:utils.py
示例8: emit
def emit(self, eventDict):
if 'failure' in eventDict:
vf = eventDict['failure']
e_t, e_v, e_tb = vf.type, vf.value, vf.getTracebackObject()
sys.excepthook(e_t, e_v, e_tb)
text = twlog.textFromEventDict(eventDict)
if text is None:
return
timeStr = self.formatTime(eventDict['time'])
fmtDict = {'system': eventDict['system'], 'text': text.replace("\n", "\n\t")}
msgStr = twlog._safeFormat("[%(system)s] %(text)s\n", fmtDict)
if GLLogObserver.suppressed == GLLogObserver.limit_suppressed:
GLLogObserver.suppressed = 0
GLLogObserver.limit_suppressed += 5
GLLogObserver.last_exception_msg = ""
try:
# in addition to escape sequence removal on logfiles we also quote html chars
util.untilConcludes(self.write, timeStr + " " + log_encode_html(msgStr))
util.untilConcludes(self.flush) # Hoorj!
except Exception as excep:
GLLogObserver.suppressed += 1
GLLogObserver.last_exception_msg = str(excep)
开发者ID:Taipo,项目名称:GlobaLeaks,代码行数:26,代码来源:utility.py
示例9: emit
def emit(self, eventDict):
if 'failure' in eventDict:
vf = eventDict['failure']
e_t, e_v, e_tb = vf.type, vf.value, vf.getTracebackObject()
sys.excepthook(e_t, e_v, e_tb)
text = twlog.textFromEventDict(eventDict)
if text is None:
return
timeStr = self.formatTime(eventDict['time'])
fmtDict = {'system': eventDict['system'], 'text': text.replace("\n", "\n\t")}
msgStr = twlog._safeFormat("[%(system)s] %(text)s\n", fmtDict)
if GLLogObserver.suppressed == GLLogObserver.limit_suppressed:
# This code path flush the status of the broken log, in the case a flood is happen
# for few moment or in the case something goes wrong when logging below.
log.info("!! has been suppressed %d log lines due to error flood (last error %s)" %
(GLLogObserver.limit_suppressed, GLLogObserver.last_exception_msg) )
GLLogObserver.suppressed = 0
GLLogObserver.limit_suppressed += 5
GLLogObserver.last_exception_msg = ""
try:
# in addition to escape sequence removal on logfiles we also quote html chars
util.untilConcludes(self.write, timeStr + " " + log_encode_html(msgStr))
util.untilConcludes(self.flush) # Hoorj!
except Exception as excep:
GLLogObserver.suppressed += 1
GLLogObserver.last_exception_msg = str(excep)
开发者ID:RuanAragao,项目名称:GlobaLeaks,代码行数:32,代码来源:utility.py
示例10: exception_msg_handler
def exception_msg_handler(signal, data):
"""
Handler for the ExceptionSignal signal.
:param signal: event data
:type signal: (event_type, message_data)
:param data: additional data
:type data: any
"""
global exception_processed
if exception_processed:
# get data from the event data structure
exception_info = signal.exception_info
stack_trace = "\n" + App.get_scheduler().dump_stack()
log.error(stack_trace)
# exception_info is a list
sys.excepthook(*exception_info)
else:
# show only the first exception do not spam user with others
exception_processed = True
loop = App.get_event_loop()
# start new loop for handling the exception
# this will stop processing all the old signals and prevent raising new exceptions
loop.execute_new_loop(signal)
开发者ID:zhangsju,项目名称:anaconda,代码行数:25,代码来源:__init__.py
示例11: do
def do(self, s):
"""Does an arbitrary operation from a valid Chef string
The command must be the first word, case sensitive.
If the command does not exist, None is returned.
The rest of the string is passed to the desired function as a list.
Author: Sean
"""
def isVerbStatement(li):
return len(li) == 3 and li[1] == "the" and li[2] in [v + "." for v in self.ingredients]
t = s.split()
try:
if s == "Ingredients.":
self._do_ingredients()
elif len(t) < 2:
raise Kitchen.Error("Syntax Error", "Commands must have at least two tokens.")
elif hasattr(self, t[0]):
return getattr(self, t[0])(t[1:])
elif isVerbStatement(t): # the word may be a verb
print "Verbing!"
print "Verb:", t[0]
else:
print "No such attribute"
except Kitchen.Error as (title, message):
import sys
sys.excepthook(*sys.exc_info())
print ""
print "{t}: {m}\a".format(t=title, m=message)
return False
开发者ID:vermiculus,项目名称:pychef,代码行数:34,代码来源:chef.py
示例12: execute
def execute(self):
"""Execute the PEX.
This function makes assumptions that it is the last function called by
the interpreter.
"""
teardown_verbosity = self._vars.PEX_TEARDOWN_VERBOSE
try:
with self.patch_sys():
working_set = self._activate()
TRACER.log('PYTHONPATH contains:')
for element in sys.path:
TRACER.log(' %c %s' % (' ' if os.path.exists(element) else '*', element))
TRACER.log(' * - paths that do not exist or will be imported via zipimport')
with self.patch_pkg_resources(working_set):
self._wrap_coverage(self._wrap_profiling, self._execute)
except Exception:
# Allow the current sys.excepthook to handle this app exception before we tear things down in
# finally, then reraise so that the exit status is reflected correctly.
sys.excepthook(*sys.exc_info())
raise
except SystemExit as se:
# Print a SystemExit error message, avoiding a traceback in python3.
# This must happen here, as sys.stderr is about to be torn down
if not isinstance(se.code, int) and se.code is not None:
print(se.code, file=sys.stderr)
raise
finally:
# squash all exceptions on interpreter teardown -- the primary type here are
# atexit handlers failing to run because of things such as:
# http://stackoverflow.com/questions/2572172/referencing-other-modules-in-atexit
if not teardown_verbosity:
sys.stderr.flush()
sys.stderr = DevNull()
sys.excepthook = lambda *a, **kw: None
开发者ID:SeleniumHQ,项目名称:buck,代码行数:35,代码来源:pex.py
示例13: sendColormap
def sendColormap(self):
if DEBUG:
print("sending colormap")
#prevent unexpected behaviour because of bad limits
if self.minValue > self.maxValue:
vmax = self.minValue
vmin = self.maxValue
else:
vmax = self.maxValue
vmin = self.minValue
try:
#self.emit(qt.SIGNAL("ColormapChanged"),
# self.colormapIndex, self.autoscale,
# vmin, vmax,
# self.dataMin, self.dataMax,
# self.colormapType)
cmap = [self.colormapIndex, self.autoscale,
vmin, vmax,
self.dataMin, self.dataMax,
self.colormapType]
self.sigColormapChanged.emit(cmap)
except:
sys.excepthook(sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2])
开发者ID:alemirone,项目名称:pymca,代码行数:26,代码来源:ColormapDialog.py
示例14: _do_polling
def _do_polling(self):
while True:
try:
self.value_changed()
except BaseException:
sys.excepthook(*sys.exc_info())
gevent.sleep(self.interval)
开发者ID:IvarsKarpics,项目名称:HardwareRepository,代码行数:7,代码来源:Oxford700.py
示例15: _do_polling
def _do_polling(self):
while True:
try:
self.poll()
except:
sys.excepthook(*sys.exc_info())
time.sleep(self.getProperty("interval")/1000.0 or 1)
开发者ID:IvarsKarpics,项目名称:HardwareObjects,代码行数:7,代码来源:ID29HutchTrigger.py
示例16: _enum_dir_cb
def _enum_dir_cb(self, fileenum, result, results):
try:
files = fileenum.next_files_finish(result)
if files is None or len(files) == 0:
print("okay, done; got %d files" % len(results))
fileenum.close_async(GLib.PRIORITY_DEFAULT, None, self._close_enum_cb, None)
self.finished(results)
return
for f in files:
ct = f.get_attribute_string("standard::content-type")
# assume readable unless told otherwise
readable = True
if f.has_attribute("access::can-read"):
readable = f.get_attribute_boolean("access::can-read")
if ct is not None and ct.startswith("image/") and readable:
results.append(f.get_name())
fileenum.next_files_async(ITEMS_PER_NOTIFICATION, GLib.PRIORITY_DEFAULT, None, self._enum_dir_cb, results)
except Exception as e:
print("okay, probably done: %s" % e)
import sys
sys.excepthook(*sys.exc_info())
self.finished(results)
fileenum.close_async(GLib.PRIORITY_DEFAULT, None, self._close_enum_cb, None)
开发者ID:GNOME,项目名称:rhythmbox,代码行数:25,代码来源:local.py
示例17: load
def load():
try:
f = open(fullfn)
except IOError: # e.g. file-not-found. that's ok
return baseType(*defaultArgs)
# some common types
g = {baseType.__name__: baseType} # the baseType itself
if namespace is None:
g.update(globals()) # all what we have here
if baseType.__module__:
# the module of the basetype
import sys
m = sys.modules[baseType.__module__]
g.update([(varname,getattr(m,varname)) for varname in dir(m)])
else:
g.update(namespace)
try:
obj = eval(f.read(), g)
except Exception:
import sys
sys.excepthook(*sys.exc_info())
return baseType(*defaultArgs)
# Try to convert.
if not isinstance(obj, baseType):
obj = baseType(obj)
return obj
开发者ID:BMXE,项目名称:music-player,代码行数:28,代码来源:utils.py
示例18: update
def update(ev=None, args=None, kwargs=None):
control.subjectObject = control.attr.__get__(control.parent.subjectObject)
s = "???"
try:
labelContent = control.getTextObj()
s = convertToUnicode(labelContent)
except Exception:
sys.excepthook(*sys.exc_info())
def do_update():
label.setStringValue_(s)
if backgroundColor(control):
label.setDrawsBackground_(True)
label.setBackgroundColor_(backgroundColor(control))
label.setTextColor_(foregroundColor(control))
if control.attr.autosizeWidth:
label.sizeToFit()
control.layoutLine()
if label.onMouseEntered or label.onMouseExited:
if getattr(label, "trackingRect", None):
label.removeTrackingRect_(label.trackingRect)
label.trackingRect = label.addTrackingRect_owner_userData_assumeInside_(label.bounds(), label, None, False)
do_in_mainthread(do_update, wait=False)
开发者ID:chunqishi,项目名称:music-player,代码行数:26,代码来源:guiCocoa.py
示例19: run
def run(self):
global path, version, initVersion, forcedVersion
global buildVersion
## Make sure build directory is clean
buildPath = os.path.join(path, self.build_lib)
if os.path.isdir(buildPath):
distutils.dir_util.remove_tree(buildPath)
ret = build.build.run(self)
# If the version in __init__ is different from the automatically-generated
# version string, then we will update __init__ in the build directory
if initVersion == version:
return ret
try:
initfile = os.path.join(buildPath, 'pyqtgraph', '__init__.py')
data = open(initfile, 'r').read()
open(initfile, 'w').write(re.sub(r"__version__ = .*", "__version__ = '%s'" % version, data))
buildVersion = version
except:
if forcedVersion:
raise
buildVersion = initVersion
sys.stderr.write("Warning: Error occurred while setting version string in build path. "
"Installation will use the original version string "
"%s instead.\n" % (initVersion)
)
sys.excepthook(*sys.exc_info())
return ret
开发者ID:AeroEng43,项目名称:pyqtgraph,代码行数:31,代码来源:setup.py
示例20: onTextChange
def onTextChange():
try:
control.subjectObject = control.attr.__get__(control.parent.subjectObject)
newText = unicode(label.stringValue())
control.subjectObject(updateText = newText)
except Exception:
sys.excepthook(*sys.exc_info())
开发者ID:chunqishi,项目名称:music-player,代码行数:7,代码来源:guiCocoa.py
注:本文中的sys.excepthook函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论