當前位置: 首頁>>代碼示例>>Python>>正文


Python traceback.format_exc方法代碼示例

本文整理匯總了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 
開發者ID:toolforge,項目名稱:video2commons,代碼行數:24,代碼來源:app.py

示例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()) 
開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:23,代碼來源:diagnose.py

示例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()) 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:19,代碼來源:registry_test.py

示例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 
開發者ID:gradiuscypher,項目名稱:bounty_tools,代碼行數:27,代碼來源:reconng.py

示例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) 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:27,代碼來源:app.py

示例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()) 
開發者ID:scrapbird,項目名稱:sarlacc,代碼行數:18,代碼來源:plugin_manager.py

示例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)) 
開發者ID:huge-success,項目名稱:sanic,代碼行數:26,代碼來源:server.py

示例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() 
開發者ID:atareao,項目名稱:daily-wallpaper,代碼行數:18,代碼來源:fsync.py

示例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 
開發者ID:OpenTrading,項目名稱:OpenTrader,代碼行數:18,代碼來源:OTBackTest.py

示例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 
開發者ID:wolfmanjm,項目名稱:kivy-smoothie-host,代碼行數:21,代碼來源:main.py

示例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())) 
開發者ID:wolfmanjm,項目名稱:kivy-smoothie-host,代碼行數:22,代碼來源:main.py

示例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())) 
開發者ID:wolfmanjm,項目名稱:kivy-smoothie-host,代碼行數:18,代碼來源:main.py

示例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()) 
開發者ID:wolfmanjm,項目名稱:kivy-smoothie-host,代碼行數:26,代碼來源:comms-net.py

示例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 
開發者ID:ooterness,項目名稱:DualFisheye,代碼行數:18,代碼來源:fisheye.py

示例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())) 
開發者ID:arnaudin,項目名稱:fusion360-airfoil-generator,代碼行數:23,代碼來源:fusion360-airfoil-generator-addin.py


注:本文中的traceback.format_exc方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。