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 vote down vote up
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 vote down vote up
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: reconng.py    From bounty_tools with MIT License 7 votes vote down vote up
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 #4
Source File: plugin_manager.py    From sarlacc with MIT License 7 votes vote down vote up
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 #5
Source File: server.py    From sanic with MIT License 7 votes vote down vote up
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 #6
Source File: OTBackTest.py    From OpenTrader with GNU Lesser General Public License v3.0 7 votes vote down vote up
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 #7
Source File: main.py    From kivy-smoothie-host with GNU General Public License v3.0 7 votes vote down vote up
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: main.py    From kivy-smoothie-host with GNU General Public License v3.0 7 votes vote down vote up
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 #9
Source File: main.py    From kivy-smoothie-host with GNU General Public License v3.0 7 votes vote down vote up
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 #10
Source File: comms-net.py    From kivy-smoothie-host with GNU General Public License v3.0 7 votes vote down vote up
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 #11
Source File: fusion360-airfoil-generator-script.py    From fusion360-airfoil-generator with MIT License 7 votes vote down vote up
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 #12
Source File: fusion360-airfoil-generator-script.py    From fusion360-airfoil-generator with MIT License 7 votes vote down vote up
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 #13
Source File: app.py    From video2commons with GNU General Public License v3.0 6 votes vote down vote up
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: diagnose.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: registry_test.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
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: fisheye.py    From DualFisheye with MIT License 6 votes vote down vote up
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 #17
Source File: fusion360-airfoil-generator-addin.py    From fusion360-airfoil-generator with MIT License 6 votes vote down vote up
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 #18
Source File: project_module.py    From pyspider with Apache License 2.0 6 votes vote down vote up
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 vote down vote up
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 vote down vote up
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: tasks.py    From drydock with Apache License 2.0 5 votes vote down vote up
def on_get(self, req, resp):
        """Handler for GET method."""
        try:
            task_model_list = self.state_manager.get_tasks()
            task_list = [x.to_dict() for x in task_model_list]
            resp.body = json.dumps(task_list)
            resp.status = falcon.HTTP_200
        except Exception as ex:
            self.error(
                req.context,
                "Unknown error: %s\n%s" % (str(ex), traceback.format_exc()))
            self.return_error(
                resp, falcon.HTTP_500, message="Unknown error", retry=False) 
Example #22
Source File: tasks.py    From drydock with Apache License 2.0 5 votes vote down vote up
def on_post(self, req, resp):
        """Handler for POST method."""
        # A map of supported actions to the handlers for tasks for those actions
        supported_actions = {
            'validate_design': TasksResource.task_validate_design,
            'verify_site': TasksResource.task_verify_site,
            'prepare_site': TasksResource.task_prepare_site,
            'verify_nodes': TasksResource.task_verify_nodes,
            'prepare_nodes': TasksResource.task_prepare_nodes,
            'deploy_nodes': TasksResource.task_deploy_nodes,
            'destroy_nodes': TasksResource.task_destroy_nodes,
            'relabel_nodes': TasksResource.task_relabel_nodes,
        }

        try:
            json_data = self.req_json(req)

            action = json_data.get('action', None)
            if supported_actions.get(action, None) is None:
                self.error(req.context, "Unsupported action %s" % action)
                self.return_error(
                    resp,
                    falcon.HTTP_400,
                    message="Unsupported action %s" % action,
                    retry=False)
            else:
                supported_actions.get(action)(self, req, resp, json_data)
        except Exception as ex:
            self.error(
                req.context,
                "Unknown error: %s\n%s" % (str(ex), traceback.format_exc()))
            self.return_error(
                resp, falcon.HTTP_500, message="Unknown error", retry=False) 
Example #23
Source File: __init__.py    From aegea with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    parsed_args = parser.parse_args(args=args)
    logger.setLevel(parsed_args.log_level)
    has_attrs = (getattr(parsed_args, "sort_by", None) and getattr(parsed_args, "columns", None))
    if has_attrs and parsed_args.sort_by not in parsed_args.columns:
        parsed_args.columns.append(parsed_args.sort_by)
    try:
        result = parsed_args.entry_point(parsed_args)
    except Exception as e:
        if isinstance(e, NoRegionError):
            msg = "The AWS CLI is not configured."
            msg += " Please configure it using instructions at"
            msg += " http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html"
            exit(msg)
        elif logger.level < logging.ERROR:
            raise
        else:
            err_msg = traceback.format_exc()
            try:
                err_log_filename = os.path.join(config.user_config_dir, "error.log")
                with open(err_log_filename, "ab") as fh:
                    print(datetime.datetime.now().isoformat(), file=fh)
                    print(err_msg, file=fh)
                exit("{}: {}. See {} for error details.".format(e.__class__.__name__, e, err_log_filename))
            except Exception:
                print(err_msg, file=sys.stderr)
                exit(os.EX_SOFTWARE)
    if isinstance(result, SystemExit):
        raise result
    elif result is not None:
        if isinstance(result, dict) and "ResponseMetadata" in result:
            del result["ResponseMetadata"]
        print(json.dumps(result, indent=2, default=str)) 
Example #24
Source File: automate.py    From aospy with Apache License 2.0 5 votes vote down vote up
def _compute_or_skip_on_error(calc, compute_kwargs):
    """Execute the Calc, catching and logging exceptions, but don't re-raise.

    Prevents one failed calculation from stopping a larger requested set
    of calculations.
    """
    try:
        return calc.compute(**compute_kwargs)
    except Exception:
        msg = ("Skipping aospy calculation `{0}` due to error with the "
               "following traceback: \n{1}")
        logging.warning(msg.format(calc, traceback.format_exc()))
        return None 
Example #25
Source File: server.py    From BASS with GNU General Public License v2.0 5 votes vote down vote up
def job_create():
    try:
        job = bass.create_job()
        return jsonify(message = "ok", job = job.json())
    except Exception as ex:
        return make_response(jsonify(message = str(ex), trace = traceback.format_exc()), 400) 
Example #26
Source File: server.py    From BASS with GNU General Public License v2.0 5 votes vote down vote up
def job_get_status(job_id):
    try:
        return jsonify(message = "ok", job = bass.get_job(job_id).json())
    except KeyError:
        return make_response(jsonify(message = "Invalid job id"), 400)
    except Exception as ex:
        return make_response(jsonify(message = str(ex), trace = traceback.format_exc()), 400) 
Example #27
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def dump_zmirror_snapshot(folder="error_dump", msg=None, our_response=None):
    """
    dump当前状态到文件
    :param folder: 文件夹名
    :type folder: str
    :param our_response: Flask返回对象, 可选
    :type our_response: Response
    :param msg: 额外的信息
    :type msg: str
    :return: dump下来的文件绝对路径
    :rtype: Union[str, None]
    """
    import pickle
    try:
        if not os.path.exists(zmirror_root(folder)):
            os.mkdir(zmirror_root(folder))
        _time_str = datetime.now().strftime('snapshot_%Y-%m-%d_%H-%M-%S')

        import config

        snapshot = {
            "time": datetime.now(),
            "parse": parse.dump(),
            "msg": msg,
            "traceback": traceback.format_exc(),
            "config": attributes(config, to_dict=True),
            "FlaskRequest": attributes(request, to_dict=True),
        }
        if our_response is not None:
            our_response.freeze()
        snapshot["OurResponse"] = our_response

        dump_file_path = os.path.abspath(os.path.join(zmirror_root(folder), _time_str + '.dump'))

        with open(dump_file_path, 'wb') as fp:
            pickle.dump(snapshot, fp, pickle.HIGHEST_PROTOCOL)
        return dump_file_path
    except:
        return None 
Example #28
Source File: dataset_tool.py    From disentangling_conditional_gans with MIT License 5 votes vote down vote up
def __init__(self):
        self.value = sys.exc_info()[1]
        self.traceback = traceback.format_exc()

#---------------------------------------------------------------------------- 
Example #29
Source File: dummy_handler.py    From Turku-neural-parser-pipeline with Apache License 2.0 5 votes vote down vote up
def process(self,txt):
        try:
            resp=self.parser.parse_text(txt)
        except:
            self.send_response(500,"Internal server error")
            self.end_headers()
            self.wfile.write(traceback.format_exc().encode("utf-8"))
            self.wfile.flush()
            self.close_connection=True
            return

        self.send_response(200, 'OK')
        self.send_header("Content-type", "text/plain; charset=utf-8")
        self.end_headers()
        self.wfile.write(resp.encode("utf-8"))
        self.wfile.flush()
        self.close_connection=True 
Example #30
Source File: dummy_handler.py    From Turku-neural-parser-pipeline with Apache License 2.0 5 votes vote down vote up
def do_POST(self):
        try:
            content_length = int(self.headers['Content-Length'])
            txt=self.rfile.read(content_length).decode("utf-8")
            sys.stderr.flush()
        except:
            self.send_response(400, 'Bad request')
            self.end_headers()
            self.wfile.write(traceback.format_exc().encode("utf-8"))
            self.close_connection=True
            return
        self.process(txt)