本文整理汇总了Python中sys._exc_info函数的典型用法代码示例。如果您正苦于以下问题:Python _exc_info函数的具体用法?Python _exc_info怎么用?Python _exc_info使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_exc_info函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self, sleep=0, mode=None, log=True, __self=None):
if __self is not None:
self = __self
if not mode == "T":
if os.name == "posix":
signal(SIGHUP, self._signal)
signal(SIGINT, self._signal)
signal(SIGTERM, self._signal)
self._running = True
self.push(Started(self, mode))
try:
while self.running:
try:
[f() for f in self._ticks.copy()]
self._flush()
if sleep:
try:
time.sleep(sleep)
except:
pass
except (KeyboardInterrupt, SystemExit):
self._running = False
except:
try:
if log:
self.push(Error(*_exc_info()))
finally:
self._flush()
finally:
try:
self.push(Stopped(self))
rtime = time.time()
while len(self) > 0 and (time.time() - rtime) < 3:
try:
[f() for f in self._ticks.copy()]
self._flush()
if sleep:
time.sleep(sleep)
rtime = time.time()
except:
try:
if log:
self.push(Error(*_exc_info()))
finally:
self._flush()
except:
pass
示例2: get_error_page
def get_error_page(status, **kwargs):
"""Return an HTML page, containing a pretty error response.
status should be an int or a str.
kwargs will be interpolated into the page template.
"""
import cherrypy
try:
code, reason, message = _httputil.valid_status(status)
except ValueError:
raise cherrypy.HTTPError(500, _exc_info()[1].args[0])
# We can't use setdefault here, because some
# callers send None for kwarg values.
if kwargs.get('status') is None:
kwargs['status'] = "%s %s" % (code, reason)
if kwargs.get('message') is None:
kwargs['message'] = message
if kwargs.get('traceback') is None:
kwargs['traceback'] = ''
if kwargs.get('version') is None:
kwargs['version'] = cherrypy.__version__
for k, v in iteritems(kwargs):
if v is None:
kwargs[k] = ""
else:
kwargs[k] = _escape(kwargs[k])
# Use a custom template or callable for the error page?
pages = cherrypy.serving.request.error_page
error_page = pages.get(code) or pages.get('default')
if error_page:
try:
if hasattr(error_page, '__call__'):
return error_page(**kwargs)
else:
data = open(error_page, 'rb').read()
return tonative(data) % kwargs
except:
e = _format_exception(*_exc_info())[-1]
m = kwargs['message']
if m:
m += "<br />"
m += "In addition, the custom error page failed:\n<br />%s" % e
kwargs['message'] = m
return _HTTPErrorTemplate % kwargs
示例3: format_exc
def format_exc(exc = None):
if exc is None:
exc = _exc_info()
if exc == (None, None, None):
return ''
import traceback
return ''.join(traceback.format_exception(*exc))
示例4: unexpected_json_error_handler
def unexpected_json_error_handler():
"""request.error_response"""
(typ, value, tb) = _exc_info()
if typ:
debug = False
if hasattr(cherrypy.request, 'params'):
params = cherrypy.request.params
debug = 'debug' in params and params['debug']
response = cherrypy.response
response.headers['Content-Type'] = 'application/json'
response.headers.pop('Content-Length', None)
content = {}
if isinstance(value, ExtendedHTTPError):
content.update({'errors': value.errors})
if isinstance(typ, cherrypy.HTTPError):
cherrypy._cperror.clean_headers(value.code)
response.status = value.status
content.update({'code': value.code, 'reason': value.reason,
'message': value._message})
elif isinstance(typ, (TypeError, ValueError, KeyError)):
cherrypy._cperror.clean_headers(400)
response.status = 400
reason, default_message = _httputil.response_codes[400]
content = {'code': 400, 'reason': reason,
'message': value.message or default_message}
if cherrypy.serving.request.show_tracebacks or debug:
tb = _format_exc()
content['traceback'] = tb
response.body = json.dumps(content).encode('utf-8')
示例5: _send
def _send(self, event, channel, errors=False, log=True):
eargs = event.args
ekwargs = event.kwargs
r = False
for handler in self._getHandlers(channel):
try:
#stime = time.time()
if handler._passEvent:
r = handler(event, *eargs, **ekwargs)
else:
r = handler(*eargs, **ekwargs)
#etime = time.time()
#ttime = (etime - stime) * 1e3
#print "%s: %0.02f ms" % (reprhandler(handler), ttime)
except (KeyboardInterrupt, SystemExit):
raise
except:
if log:
etype, evalue, etraceback = _exc_info()
self.push(Error(etype, evalue, etraceback, handler=handler))
if errors:
raise
else:
_exc_clear()
if r is not None and r and handler.filter:
return r
return r
示例6: format_exc
def format_exc(exc=None):
"""Return exc (or sys.exc_info if None), formatted."""
if exc is None:
exc = _exc_info()
if exc == (None, None, None):
return ""
import traceback
return "".join(traceback.format_exception(*exc))
示例7: tick
def tick(self):
if self._ticks:
try:
[f() for f in self._ticks.copy()]
except:
etype, evalue, etraceback = _exc_info()
self.fire(Error(etype, evalue, format_tb(etraceback)))
if self:
self._flush()
示例8: format_exc
def format_exc(exc=None):
"""Return exc (or sys.exc_info if None), formatted."""
try:
if exc is None:
exc = _exc_info()
if exc == (None, None, None):
return ''
import traceback
return ''.join(traceback.format_exception(*exc))
finally:
del exc
示例9: _on_request
def _on_request(self, event, req, res):
if not self.apps:
return
parts = req.path.split("/")
candidates = []
for i in range(len(parts)):
k = "/".join(parts[:(i + 1)]) or "/"
if k in self.apps:
candidates.append((k, self.apps[k]))
candidates = sorted(candidates, key=itemgetter(0), reverse=True)
if not candidates:
return
path, app = candidates[0]
buffer = StringIO()
def start_response(status, headers, exc_info=None):
res.status = int(status.split(" ", 1)[0])
for header in headers:
res.headers.add_header(*header)
return buffer.write
errors = self.errors[path]
environ = create_environ(errors, path, req)
try:
body = app(environ, start_response)
if isinstance(body, list):
_body = type(body[0])() if body else ""
body = _body.join(body)
elif isinstance(body, GeneratorType):
res.body = body
res.stream = True
return res
if not body:
if not buffer.tell():
return empty
else:
buffer.seek(0)
return buffer
else:
return body
except Exception as error:
etype, evalue, etraceback = _exc_info()
error = (etype, evalue, format_tb(etraceback))
return httperror(req, res, 500, error=error)
finally:
event.stop()
示例10: get_traceback_string
def get_traceback_string():
"""
Gibt den Traceback-String des letzten Fehlers zurück
"""
from sys import exc_info as _exc_info
exc = _exc_info()
if exc == (None, None, None):
return ""
import traceback
tb = "".join(traceback.format_exception(*exc))
# Fertig
return tb
示例11: _on_request
def _on_request(self, event, request, response):
if self.path and not request.path.startswith(self.path):
return
req = event
path = request.path
if self.path is not None:
path = path[len(self.path):]
req.path = path
self._request = request
self._response = response
try:
return self.app(self.createEnviron(), self.start_response)
except Exception, error:
status = 500
message = str(error)
error = _exc_info()
etype, evalue, etraceback = _exc_info()
error = (etype, evalue, format_tb(etraceback))
return HTTPError(request, response, status, message, error)
示例12: get_traceback_string
def get_traceback_string():
"""
Returns the traceback unicode string for the last error
"""
from sys import exc_info as _exc_info
exc = _exc_info()
if exc == (None, None, None):
return ""
import traceback
tb = "".join(traceback.format_exception(*exc))
# Fertig
return unicode(tb, errors = "replace")
示例13: __init__
def __init__(self, status=500, message=None):
self.status = status
try:
self.code, self.reason, defaultmsg = _httputil.valid_status(status)
except ValueError:
raise self.__class__(500, _exc_info()[1].args[0])
if self.code < 400 or self.code > 599:
raise ValueError("status must be between 400 and 599.")
# See http://www.python.org/dev/peps/pep-0352/
# self.message = message
self._message = message or defaultmsg
CherryPyException.__init__(self, status, message)
示例14: run
def run(self, sleep=0, mode=None, errors=False, log=True, __self=None):
if __self is not None:
self = __self
if not mode == "T":
#signal(SIGHUP, self._signal)
signal(SIGINT, self._signal)
signal(SIGTERM, self._signal)
self._running = True
self.push(Started(self, mode), "started")
try:
while self._running:
try:
[f() for f in self.ticks.copy()]
self.flush()
if sleep:
try:
time.sleep(sleep)
except:
pass
except (KeyboardInterrupt, SystemExit):
self._running = False
except:
try:
if log:
self.push(Error(*_exc_info()), "error")
if errors:
raise
else:
_exc_clear()
except:
pass
finally:
try:
self.push(Stopped(self), "stopped")
rtime = time.time()
while len(self) > 0 and (time.time() - rtime) < 3:
[f() for f in self.ticks.copy()]
self.flush()
if sleep:
time.sleep(sleep)
rtime = time.time()
except:
pass
示例15: handle_error
def handle_error():
"""
Note:
Not catch Httpd code 3XX~4XX exception. These exception will just response to client.
"""
excpetion_inst = _exc_info()[1]
if isinstance(excpetion_inst, RequestError):
cherrypy.response.headers['Content-Type'] = 'application/json'
cherrypy.response.status = excpetion_inst.http_status
resp = Response(success=False, err_code=excpetion_inst.code, err_msg=excpetion_inst.get_msg())
cherrypy.response.body = json.dumps(resp)
else: # hide exception information
cherrypy.response.show_tracebacks = False
cherrypy.response.status = 500
cherrypy.response.body = [
"<html><body>%s</body></html>" % ERR_MSG[500]
]