Python traceback.format_exc() Examples
The following are 30
code examples of traceback.format_exc().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
traceback
, or try the search function
.
Example #1
Source File: app.py From botbuilder-python with MIT License | 8 votes |
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)
Example #2
Source File: fsync.py From daily-wallpaper with MIT License | 8 votes |
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()
Example #3
Source File: main.py From kivy-smoothie-host with GNU General Public License v3.0 | 7 votes |
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()))
Example #4
Source File: OTBackTest.py From OpenTrader with GNU Lesser General Public License v3.0 | 7 votes |
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
Example #5
Source File: comms-net.py From kivy-smoothie-host with GNU General Public License v3.0 | 7 votes |
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())
Example #6
Source File: reconng.py From bounty_tools with MIT License | 7 votes |
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
Example #7
Source File: main.py From kivy-smoothie-host with GNU General Public License v3.0 | 7 votes |
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
Example #8
Source File: fusion360-airfoil-generator-script.py From fusion360-airfoil-generator with MIT License | 7 votes |
def run(context): try: commandDefinitions = ui.commandDefinitions #check the command exists or not cmdDef = commandDefinitions.itemById('Airfoil') if not cmdDef: cmdDef = commandDefinitions.addButtonDefinition('Airfoil', 'Create Airfoil', 'Create an airfoil.', './resources') # relative resource file path is specified onCommandCreated = AirfoilCommandCreatedHandler() cmdDef.commandCreated.add(onCommandCreated) # keep the handler referenced beyond this function handlers.append(onCommandCreated) inputs = adsk.core.NamedValues.create() cmdDef.execute(inputs) # prevent this module from being terminate when the script returns, because we are waiting for event handlers to fire adsk.autoTerminate(False) except: if ui: ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
Example #9
Source File: plugin_manager.py From sarlacc with MIT License | 7 votes |
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())
Example #10
Source File: fusion360-airfoil-generator-script.py From fusion360-airfoil-generator with MIT License | 7 votes |
def notify(self, args): try: cmd = args.command onExecute = AirfoilCommandExecuteHandler() cmd.execute.add(onExecute) onDestroy = AirfoilCommandDestroyHandler() cmd.destroy.add(onDestroy) # keep the handler referenced beyond this function handlers.append(onExecute) handlers.append(onDestroy) #define the UI inputs inputs = cmd.commandInputs inputs.addStringValueInput('airfoilProfile', 'NACA profile', defaultAirfoilProfile) inputs.addStringValueInput('airfoilNumPts', 'Points per side', str(defaultAirfoilNumPts)) inputs.addBoolValueInput('airfoilHalfCosine', 'Half cosine spacing', True, '', defaultAirfoilHalfCosine) inputs.addBoolValueInput('airfoilFT', 'Finite thickness TE', True, '', defaultAirfoilFT) except: if ui: ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
Example #11
Source File: main.py From kivy-smoothie-host with GNU General Public License v3.0 | 7 votes |
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()))
Example #12
Source File: server.py From sanic with MIT License | 7 votes |
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))
Example #13
Source File: app.py From video2commons with GNU General Public License v3.0 | 6 votes |
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
Example #14
Source File: fisheye.py From DualFisheye with MIT License | 6 votes |
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
Example #15
Source File: registry_test.py From DOTA_models with Apache License 2.0 | 6 votes |
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())
Example #16
Source File: fusion360-airfoil-generator-addin.py From fusion360-airfoil-generator with MIT License | 6 votes |
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()))
Example #17
Source File: diagnose.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
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())
Example #18
Source File: project_module.py From pyspider with Apache License 2.0 | 6 votes |
def _load_project(self, project): '''Load project into self.projects from project info dict''' try: project['md5sum'] = utils.md5string(project['script']) ret = self.build_module(project, self.env) self.projects[project['name']] = ret except Exception as e: logger.exception("load project %s error", project.get('name', None)) ret = { 'loader': None, 'module': None, 'class': None, 'instance': None, 'exception': e, 'exception_log': traceback.format_exc(), 'info': project, 'load_time': time.time(), } self.projects[project['name']] = ret return False logger.debug('project: %s updated.', project.get('name', None)) return True
Example #19
Source File: timer_queue.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def check_and_execute(self): ''' Get expired timers and execute callbacks for the timers. :returns: duration of next expired timer. :rtype: ``float`` ''' (next_expired_time, expired_timers) = self.get_expired_timers() for timer in expired_timers: try: timer() except Exception: logging.error(traceback.format_exc()) self.reset_timers(expired_timers) return _calc_sleep_time(next_expired_time)
Example #20
Source File: timer_queue.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def _check_and_execute(self): wakeup_queue = self._wakeup_queue while 1: (next_expired_time, expired_timers) = self._get_expired_timers() for timer in expired_timers: try: # Note, please make timer callback effective/short timer() except Exception: logging.error(traceback.format_exc()) self._reset_timers(expired_timers) sleep_time = _calc_sleep_time(next_expired_time) try: wakeup = wakeup_queue.get(timeout=sleep_time) if wakeup is TEARDOWN_SENTINEL: break except Queue.Empty: pass logging.info('TimerQueue stopped.')
Example #21
Source File: fisheye.py From DualFisheye with MIT License | 5 votes |
def _adjust_lens1(self): self._destroy(self.win_lens1) try: self.win_lens1 = tk.Toplevel(self.parent) FisheyeAlignmentGUI(self.win_lens1, self.img1.get(), self.lens1) except IOError: self._destroy(self.win_lens1) tkMessageBox.showerror('Error', 'Unable to read image file #1.') except: self._destroy(self.win_lens1) tkMessageBox.showerror('Dialog creation error', traceback.format_exc())
Example #22
Source File: pyjstat.py From pyjstat with Apache License 2.0 | 5 votes |
def request(path, verify=True): """Send a request to a given URL accepting JSON format. Args: path (str): The URI to be requested. Returns: response: Deserialized JSON Python object. Raises: HTTPError: the HTTP error returned by the requested server. InvalidURL: an invalid URL has been requested. Exception: generic exception. """ headers = {'Accept': 'application/json'} try: requested_object = requests.get(path, headers=headers, verify=verify) requested_object.raise_for_status() except requests.exceptions.HTTPError as exception: LOGGER.error((inspect.stack()[0][3]) + ': HTTPError = ' + str(exception.response.status_code) + ' ' + str(exception.response.reason) + ' ' + str(path)) raise except requests.exceptions.InvalidURL as exception: LOGGER.error('URLError = ' + str(exception.reason) + ' ' + str(path)) raise except Exception: import traceback LOGGER.error('Generic exception: ' + traceback.format_exc()) raise else: response = requested_object.json() return response
Example #23
Source File: cli_msg_printer.py From VxAPI with GNU General Public License v3.0 | 5 votes |
def print_error_info(e): print(Color.control('During the code execution, error has occurred. Please try again or contact the support.'), file=sys.stderr) print(Color.error('Message: \'{}\'.').format(str(e)) + '\n', file=sys.stderr) print(traceback.format_exc(), file=sys.stderr)
Example #24
Source File: console.py From ishell with MIT License | 5 votes |
def loop(self): previous_completer = readline.get_completer() readline.parse_and_bind("tab: complete") readline.set_completer(self.walk) prompt = self.prompt + self.prompt_delim if not ishell._current_prompt: previous_prompt = prompt else: previous_prompt = ishell._current_prompt ishell._current_prompt = prompt if self.welcome_message: sys.stdout.write(self.welcome_message + "\n\r") while 1: try: sys.stdout.write("\r") if self._exit: break sys.stdout.write("\033[K") input_ = input(prompt + " ") if not input_.strip(): self.print_childs_help() elif input_ in ('quit', 'exit'): break else: self.walk_and_run(input_) except (KeyboardInterrupt, EOFError): print("exit") break except Exception: print(traceback.format_exc()) sys.exit(1) ishell._current_prompt = previous_prompt readline.set_completer(previous_completer)
Example #25
Source File: fisheye.py From DualFisheye with MIT License | 5 votes |
def save_config(self, filename=None): if filename is None: file_obj = tkFileDialog.asksaveasfile() if file_obj is None: return else: file_obj = open(filename, 'w') try: save_config(file_obj, self.lens1, self.lens2) except: tkMessageBox.showerror('Config save error', traceback.format_exc()) # Render and save output in various modes.
Example #26
Source File: viewer.py From kivy-smoothie-host with GNU General Public License v3.0 | 5 votes |
def _load_file(self, ll): self._loaded_ok = False try: self.parse_gcode_file(self.app.gcode_file, ll, True) except Exception: print(traceback.format_exc()) mb = MessageBox(text='File not found: {}'.format(self.app.gcode_file)) mb.open() self._loaded()
Example #27
Source File: web_server.py From kivy-smoothie-host with GNU General Public License v3.0 | 5 votes |
def _start(self): ip = get_ip() logger.info("ProgressServer: IP address is: {}".format(ip)) RequestHandlerClass = make_request_handler_class(self.app, ip) self.myServer = HTTPServer(("", self.port), RequestHandlerClass) logger.info("ProgressServer: Web Server Starting - %s:%s" % ("", self.port)) try: self.myServer.serve_forever() except Exception: logger.warn('ProgressServer: Exception: {}'.format(traceback.format_exc())) finally: self.myServer.server_close() logger.info("ProgressServer: Web Server Stopping - %s:%s" % ("", self.port)) self.myServer = None
Example #28
Source File: main.py From kivy-smoothie-host with GNU General Public License v3.0 | 5 votes |
def _start_print(self, file_path=None, directory=None): # start comms thread to stream the file # set comms.ping_pong to False for fast stream mode if file_path is None: file_path = self.app.gcode_file if directory is None: directory = self.last_path Logger.info('MainWindow: printing file: {}'.format(file_path)) 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('>>> Running file: {}, {} lines'.format(file_path, self.nlines)) if self.app.fast_stream: self.display('>>> Using fast stream') if self.app.comms.stream_gcode(file_path, progress=lambda x: self.display_progress(x)): self.display('>>> Run started at: {}'.format(self.start_print_time.strftime('%x %X'))) else: self.display('WARNING Unable to start print') return self.set_last_file(directory, file_path) self.ids.print_but.text = 'Pause' self.is_printing = True self.paused = False
Example #29
Source File: ui.py From hiku with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _index_post(self, environ, start_response): limit = max(0, int(environ.get('CONTENT_LENGTH') or 0)) if limit > 2 ** 20: # 1MB return self._error(400, start_response, 'Payload is too big') pattern = environ['wsgi.input'].read(limit) try: # TODO: implement query validation query = read(_decode(pattern)) errors = validate(self.root, query) if errors: result = {'errors': errors} status = '400 Bad Request' else: result = self.engine.execute(self.root, query, ctx=self.ctx) result = denormalize(self.root, result) status = '200 OK' except Exception: tb = traceback.format_exc() if self.debug else None result = {'traceback': tb} status = '500 Internal Server Error' result_data = _encode(json.dumps(result)) start_response(status, [ ('Content-Type', 'application/json'), ('Content-Length', str(len(result_data))), ]) return [result_data]
Example #30
Source File: OTCmd2.py From OpenTrader with GNU Lesser General Public License v3.0 | 5 votes |
def iMain(lCmdLine): if '--test' in lCmdLine: # legacy - unused sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() unittest.main() return 0 oApp = None try: oArgParser = oParseOptions() oOptions = oArgParser.parse_args(lCmdLine) sConfigFile = oOptions.sConfigFile oConfig = oParseConfig(sConfigFile) oConfig = oMergeConfig(oConfig, oOptions) oApp = CmdLineApp(oConfig, oOptions.lArgs) if oOptions.lArgs: oApp.onecmd_plus_hooks(' '.join(oOptions.lArgs) +'\n') else: oApp._cmdloop() except KeyboardInterrupt: pass except Exception as e: print traceback.format_exc(10) # always reached if oApp: oApp.vAtexit() l = threading.enumerate() if len(l) > 1: print "WARN: Threads still running: %r" % (l,)