本文整理汇总了Python中traceback.format_exc方法的典型用法代码示例。如果您正苦于以下问题:Python traceback.format_exc方法的具体用法?Python traceback.format_exc怎么用?Python traceback.format_exc使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类traceback
的用法示例。
在下文中一共展示了traceback.format_exc方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: all_exception_handler
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def all_exception_handler(e):
"""Handle an exception and show the traceback to error page."""
try:
message = 'Please file an issue in GitHub: ' + \
traceback.format_exc()
loggedin = 'username' in session
except:
message = (
'Something went terribly wrong, '
'and we failed to find the cause automatically. '
'Please file an issue in GitHub.'
)
loggedin = False
try:
return render_template(
'error.min.html',
message=message,
loggedin=loggedin
), 500
except:
return message, 500
示例2: check_mxnet
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def check_mxnet():
print('----------MXNet Info-----------')
try:
import mxnet
print('Version :', mxnet.__version__)
mx_dir = os.path.dirname(mxnet.__file__)
print('Directory :', mx_dir)
commit_hash = os.path.join(mx_dir, 'COMMIT_HASH')
with open(commit_hash, 'r') as f:
ch = f.read().strip()
print('Commit Hash :', ch)
except ImportError:
print('No MXNet installed.')
except IOError:
print('Hashtag not found. Not installed from pre-built package.')
except Exception as e:
import traceback
if not isinstance(e, IOError):
print("An error occured trying to import mxnet.")
print("This is very likely due to missing missing or incompatible library files.")
print(traceback.format_exc())
示例3: testCanCreateWithRelativePath
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def testCanCreateWithRelativePath(self):
"""Tests that Create can create the Impl subclass using a relative path."""
for name in [
PATH + 'registry_test_impl.Impl',
'syntaxnet.util.registry_test_impl.Impl',
'util.registry_test_impl.Impl',
'registry_test_impl.Impl'
]:
value = 'created via %s' % name
try:
impl = registry_test_base.Base.Create(name, value)
except ValueError:
self.fail('Create raised ValueError: %s' % traceback.format_exc())
self.assertTrue(impl is not None)
self.assertEqual(value, impl.Get())
示例4: run
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def run():
# Setup the jsonrpclib for the recon-ng RPC server, stop the API if it cannot connect to the RPC server.
try:
client = jsonrpclib.Server('http://localhost:4141')
sid = client.init()
# Get the configuration from JSON POST
content = request.get_json()
target_module = content['module']
target_domain = content['domain']
print(target_domain, target_module)
# Set the target domain
client.add('domains', target_domain, sid)
print(client.show('domains', sid))
client.use(target_module, sid)
# Execute the requested module and return the results
results = client.run(sid)
return jsonify(results)
except:
return traceback.format_exc(), 500
示例5: on_error
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
print(traceback.format_exc())
# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)
示例6: __import_module
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def __import_module(self, module_name, store):
"""Import a module
Args:
module_name -- the name of the module to load
store -- sarlacc store object (provides interface to backend storage)
"""
try:
logger.info("Loading: %s", module_name)
module = import_module("plugins." + module_name)
self.plugins.append(module.Plugin(logger, store))
logger.info("Loaded plugins/{}".format(module_name))
except Exception as e:
logger.error("Failed to load plugin/{}".format(module_name))
logger.error(traceback.format_exc())
示例7: data_received
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def data_received(self, data):
# Check for the request itself getting too large and exceeding
# memory limits
self._total_request_size += len(data)
if self._total_request_size > self.request_max_size:
self.write_error(PayloadTooLarge("Payload Too Large"))
# Create parser if this is the first time we're receiving data
if self.parser is None:
assert self.request is None
self.headers = []
self.parser = HttpRequestParser(self)
# requests count
self.state["requests_count"] = self.state["requests_count"] + 1
# Parse request chunk or close connection
try:
self.parser.feed_data(data)
except HttpParserError:
message = "Bad Request"
if self.app.debug:
message += "\n" + traceback.format_exc()
self.write_error(InvalidUsage(message))
示例8: _async_call
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def _async_call(f, args, kwargs, on_done):
def run(data):
f, args, kwargs, on_done = data
error = None
result = None
try:
result = f(*args, **kwargs)
except Exception as e:
e.traceback = traceback.format_exc()
error = 'Unhandled exception in asyn call:\n{}'.format(e.traceback)
GLib.idle_add(lambda: on_done(result, error))
data = f, args, kwargs, on_done
thread = threading.Thread(target=run, args=(data,))
thread.daemon = True
thread.start()
示例9: iMain
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def iMain():
iRetval = 0
oOm = None
try:
oOm = oOmain(sys.argv[1:])
except KeyboardInterrupt:
pass
except Exception as e:
sys.stderr.write("ERROR: " +str(e) +"\n" + \
traceback.format_exc(10) +"\n")
sys.stderr.flush()
sys.exc_clear()
iRetval = 1
finally:
if oOm: oOm.vClose()
return iRetval
示例10: _upload_gcode
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def _upload_gcode(self, file_path, dir_path):
if not file_path:
return
try:
self.nlines = Comms.file_len(file_path, self.app.fast_stream) # get number of lines so we can do progress and ETA
Logger.debug('MainWindow: number of lines: {}'.format(self.nlines))
except Exception:
Logger.warning('MainWindow: exception in file_len: {}'.format(traceback.format_exc()))
self.nlines = None
self.start_print_time = datetime.datetime.now()
self.display('>>> Uploading file: {}, {} lines'.format(file_path, self.nlines))
if not self.app.comms.upload_gcode(file_path, progress=lambda x: self.display_progress(x), done=self._upload_gcode_done):
self.display('WARNING Unable to upload file')
return
else:
self.is_printing = True
示例11: do_update
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def do_update(self):
try:
p = subprocess.Popen(['git', 'pull'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result, err = p.communicate()
if p.returncode != 0:
self.add_line_to_log(">>> Update: Failed to run git pull")
else:
need_update = True
str = result.decode('utf-8').splitlines()
self.add_line_to_log(">>> Update:")
for l in str:
self.add_line_to_log(l)
if "up-to-date" in l:
need_update = False
if need_update:
self.add_line_to_log(">>> Update: Restart may be required")
except Exception:
self.add_line_to_log(">>> Update: Error trying to update. See log")
Logger.error('MainWindow: {}'.format(traceback.format_exc()))
示例12: _load_modules
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def _load_modules(self):
if not self.config.has_section('modules'):
return
try:
for key in self.config['modules']:
Logger.info("load_modules: loading module {}".format(key))
mod = importlib.import_module('modules.{}'.format(key))
if mod.start(self.config['modules'][key]):
Logger.info("load_modules: loaded module {}".format(key))
self.loaded_modules.append(mod)
else:
Logger.info("load_modules: module {} failed to start".format(key))
except Exception:
Logger.warn("load_modules: exception: {}".format(traceback.format_exc()))
示例13: handle_temperature
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def handle_temperature(self, s):
# ok T:19.8 /0.0 @0 B:20.1 /0.0 @0
hotend_setpoint= None
bed_setpoint= None
hotend_temp= None
bed_temp= None
try:
temps = self.parse_temperature(s)
if "T" in temps and temps["T"][0]:
hotend_temp = float(temps["T"][0])
if "T" in temps and temps["T"][1]:
hotend_setpoint = float(temps["T"][1])
bed_temp = float(temps["B"][0]) if "B" in temps and temps["B"][0] else None
if "B" in temps and temps["B"][1]:
bed_setpoint = float(temps["B"][1])
self.log.debug('CommsNet: got temps hotend:{}, bed:{}, hotend_setpoint:{}, bed_setpoint:{}'.format(hotend_temp, bed_temp, hotend_setpoint, bed_setpoint))
self.app.root.update_temps(hotend_temp, hotend_setpoint, bed_temp, bed_setpoint)
except:
self.log.error(traceback.format_exc())
示例14: _auto_align_work
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def _auto_align_work(self, pan):
try:
# Repeat alignment at progressively higher resolution.
self._auto_align_step(pan, 16, 128, 'Stage 1/4')
self._auto_align_step(pan, 8, 128, 'Stage 2/4')
self._auto_align_step(pan, 4, 192, 'Stage 3/4')
self._auto_align_step(pan, 2, 256, 'Stage 4/4')
# Signal success!
self.work_status = 'Auto-alignment completed.'
self.work_error = None
self.work_done = True
except:
# Signal error.
self.work_status = 'Auto-alignment failed.'
self.work_error = traceback.format_exc()
self.work_done = True
示例15: stop
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import format_exc [as 别名]
def stop(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
objArrayPanel = []
commandControlPanel_ = commandControlByIdForPanel(commandIdOnPanel)
if commandControlPanel_:
objArrayPanel.append(commandControlPanel_)
commandDefinitionPanel_ = commandDefinitionById(commandIdOnPanel)
if commandDefinitionPanel_:
objArrayPanel.append(commandDefinitionPanel_)
for obj in objArrayPanel:
destroyObject(ui, obj)
except:
if ui:
ui.messageBox('AddIn Stop Failed: {}'.format(traceback.format_exc()))