• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python traceback.print_exc函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中traceback.print_exc函数的典型用法代码示例。如果您正苦于以下问题:Python print_exc函数的具体用法?Python print_exc怎么用?Python print_exc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了print_exc函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: run

 def run(bot):
     'parse input, update game state and call the bot classes do_turn method'
     log.info("======= GAME BEGINS ======= ")
     ants = Ants()
     map_data = ''
     while(True):
         try:
             current_line = sys.stdin.readline().rstrip('\r\n') # string new line char
             if current_line.lower() == 'ready':
                 ants.setup(map_data)
                 bot.do_setup(ants)
                 ants.finish_turn()
                 map_data = ''
             elif current_line.lower() == 'go':
                 ants.update(map_data)
                 # call the do_turn method of the class passed in
                 bot.do_turn(ants)
                 ants.finish_turn()
                 map_data = ''
             else:
                 map_data += current_line + '\n'
         except EOFError:
             break
         except KeyboardInterrupt:
             raise
         except:
             # don't raise error or return so that bot attempts to stay alive
             traceback.print_exc(file=sys.stderr)
             sys.stderr.flush()
开发者ID:vk-eipi,项目名称:ants,代码行数:29,代码来源:proj_ants_012.py


示例2: _create_database

    def _create_database(self):
        """
        Create a persistent database to store expensive parse results

        Check for Python version used to create the database is the
        same as the running python instance or re-create
        """
        project_database_file_name = join(self._output_path, "project_database")
        create_new = False
        key = b"version"
        version = str((4, sys.version)).encode()
        database = None
        try:
            database = DataBase(project_database_file_name)
            create_new = (key not in database) or (database[key] != version)
        except KeyboardInterrupt:
            raise
        except:  # pylint: disable=bare-except
            traceback.print_exc()
            create_new = True

        if create_new:
            database = DataBase(project_database_file_name, new=True)
        database[key] = version

        return PickledDataBase(database)
开发者ID:varunnagpaal,项目名称:vunit,代码行数:26,代码来源:ui.py


示例3: _import_transporter

    def _import_transporter(self, transporter):
        """Imports transporter module and class, returns class.
        Input value can be:
        * a full/absolute module path, like
          "MyTransporterPackage.SomeTransporterClass"
        """
        transporter_class = None
        module = None
        alternatives = []
        default_prefix = 'cloud_sync_app.transporter.transporter_'
        if not transporter.startswith(default_prefix):
            alternatives.append('%s%s' % (default_prefix, transporter))
        for module_name in alternatives:
            try:
                module = __import__(module_name, globals(), locals(), ["TRANSPORTER_CLASS"], -1)
            except ImportError:
                import traceback
                traceback.print_exc()
                pass

        if not module:
            msg = "The transporter module '%s' could not be found." % transporter
            if len(alternatives) > 1:
                msg = '%s Tried (%s)' % (msg, ', '.join(alternatives))
            self.logger.error(msg)
        else:
            try:
                classname = module.TRANSPORTER_CLASS
                module = __import__(module_name, globals(), locals(), [classname])
                transporter_class = getattr(module, classname)
            except AttributeError:
                self.logger.error("The Transporter module '%s' was found, but its Transporter class '%s' could not be found." % (module_name, classname))
        return transporter_class
开发者ID:cogenda,项目名称:cloud-sync,代码行数:33,代码来源:transporter_handler.py


示例4: connect

 def connect(self):
     """
     Override the connect() function to intercept calls to certain
     host/ports.
     
     If no app at host/port has been registered for interception then 
     a normal HTTPSConnection is made.
     """
     if debuglevel:
         sys.stderr.write('connect: %s, %s\n' % (self.host, self.port,))
                          
     try:
         (app, script_name) = self.get_app(self.host, self.port)
         if app:
             if debuglevel:
                 sys.stderr.write('INTERCEPTING call to %s:%s\n' % \
                                  (self.host, self.port,))
             self.sock = wsgi_fake_socket(app, self.host, self.port,
                                          script_name)
         else:
             HTTPSConnection.connect(self)
             
     except Exception, e:
         if debuglevel:              # intercept & print out tracebacks
             traceback.print_exc()
         raise
开发者ID:mozilla,项目名称:appsync-vendor,代码行数:26,代码来源:__init__.py


示例5: apply

 def apply(self,func,args):
     try:
         return func(self,*args)
     except:
         from traceback import print_exc
         print_exc()
         raise EvaluationFailedError
开发者ID:Macaulay2,项目名称:Singular,代码行数:7,代码来源:context.py


示例6: load_preferences

 def load_preferences(self):
     self.progress_callback(None, 1)
     self.progress_callback(_('Starting restoring preferences and column metadata'), 0)
     prefs_path = os.path.join(self.src_library_path, 'metadata_db_prefs_backup.json')
     if not os.path.exists(prefs_path):
         self.progress_callback(_('Cannot restore preferences. Backup file not found.'), 1)
         return False
     try:
         prefs = DBPrefs.read_serialized(self.src_library_path, recreate_prefs=False)
         db = RestoreDatabase(self.library_path, default_prefs=prefs,
                              restore_all_prefs=True,
                              progress_callback=self.progress_callback)
         db.commit()
         db.close()
         self.progress_callback(None, 1)
         if 'field_metadata' in prefs:
             self.progress_callback(_('Finished restoring preferences and column metadata'), 1)
             return True
         self.progress_callback(_('Finished restoring preferences'), 1)
         return False
     except:
         traceback.print_exc()
         self.progress_callback(None, 1)
         self.progress_callback(_('Restoring preferences and column metadata failed'), 0)
     return False
开发者ID:MarioJC,项目名称:calibre,代码行数:25,代码来源:restore.py


示例7: ruling_process

def ruling_process(queue, db, stayalive=_PROCESSOR_STAYALIVE):
    """
    :param queue: job queue. contains ids that reference the _JOBS global.
     :type queue: multiprocessing.queues.Queue
    :param stayalive: How long to keep the process running if it runs out of jobs before shutdown.
     :type stayalive: float
    :return: 
    """
    global _JOBS, _PROCESSOR_STAYALIVE
    # print("Queue: {}".format(queue))
    # print("Stayalive: {}".format(stayalive))
    # print("_JOBS: {}".format(_JOBS))
    engine = RulesProcessor(db)
    while not queue.empty():
        try:
            job_id = queue.get()
            try:
                job_params = _JOBS[job_id]
                job = RuleJob.rebuild(job_params)
                engine.process(job)
            except:
                traceback.print_exc()
                logger.warn("error processing job {}.".format(job_id))
                logger.warn("JOBS: {}".format(_JOBS))
            if queue.empty():
                time.sleep(stayalive)
        except KeyboardInterrupt:
            break
        except Exception as e:
            traceback.print_exc()
    reset_globals()
    return engine
开发者ID:riolet,项目名称:SAM,代码行数:32,代码来源:ruling_process.py


示例8: run

    def run(self, cont=0):
        # Print HTTP messages
        for key in self.http.keys():
            print '%s: %s' % (key, self.http[key])
        print

        # Redirect stderr
        sys.stderr = open(self._tempfile, 'w')

        # Grab query string
        self.get_form()

        # Function handling
        if not self.active:
            ret = _not_active(self)
            print self
            sys.exit(0)
        elif not '_no_function' in self.valid.keys():
            self.valid['_no_function'] = _no_function
        if not self.function or self.function not in self.valid.keys():
            self.function = '_no_function'
        try:
            ret = self.valid[self.function](self)
        except:
            traceback.print_exc()
            sys.stderr.flush()
            f = open(self._tempfile, 'r')
            self.title = 'CGI Error Occured'
            self.append(Pre(f.read()))
            f.close()

        # Print Document object
        print self
        if not cont:
            sys.exit(0) # Provide a speedy exit
开发者ID:senseisimple,项目名称:emulab-stable,代码行数:35,代码来源:cgiapp.py


示例9: longPollThread

	def longPollThread(self):
		connection = None
		last_url = None
		while True:
			if self.stop: return
			sleep(1)
			url = self.longPollURL
			if url != '':
				proto = self.proto
				host = self.host
				parsedUrl = urlsplit(url)
				if parsedUrl.scheme != '':
					proto = parsedUrl.scheme
				if parsedUrl.netloc != '':
					host = parsedUrl.netloc
					url = url[url.find(host)+len(host):]
					if url == '': url = '/'
				try:
					if not connection:
						connection = self.connect(proto, host, LONG_POLL_TIMEOUT)
						self.sayLine("LP connected to %s", host)
					self.longPollActive = True
					(connection, result) = self.request(connection, url, self.headers)
					self.longPollActive = False
					self.queueWork(result['result'])
					self.sayLine('long poll: new block %s%s', (result['result']['data'][56:64], result['result']['data'][48:56]))
					last_url = self.longPollURL
				except NotAuthorized:
					self.sayLine('long poll: Wrong username or password')
				except RPCError as e:
					self.sayLine('long poll: %s', e)
				except (IOError, httplib.HTTPException, ValueError):
					self.sayLine('long poll exception:')
					traceback.print_exc()
开发者ID:enolan,项目名称:poclbm,代码行数:34,代码来源:BitcoinMiner.py


示例10: dump_raw

def dump_raw():
    try:
        mp = MPTable()
        s = "MP Table -- Raw bytes and structure decode.\n\n"
        if mp:
            s += str(mp.floating_pointer) + '\n'
            s += bits.dumpmem(mp._floating_pointer_memory) + '\n'

            s += str(mp.header) + '\n'
            s += bits.dumpmem(mp._base_header_memory) + '\n'

            for base_struct in mp.base_structures:
                s += str(base_struct) + '\n'
                s += bits.dumpmem(base_struct.raw_data) + '\n'

            if mp.header.extended_table_length:
                for extended_struct in mp.extended_structures:
                    s += str(extended_struct) + '\n'
                    s += bits.dumpmem(extended_struct.raw_data)  + '\n'
        else:
            s += "MP Table not found.\n"
        ttypager.ttypager_wrap(s, indent=False)
    except:
        print("Error parsing MP Table information:")
        import traceback
        traceback.print_exc()
开发者ID:Tourountzis,项目名称:bits,代码行数:26,代码来源:mptable.py


示例11: onecmd

    def onecmd(self, s):
        # do standard parsing of line
        name, line, all = self.parseline(s)

        # look up the method
        method = getattr(self, "do_%s" % name, None)

        # if a proper method was found, try and call it.
        if method is not None and callable(method):
            # parse arguments and keyword arguments from line
            args, kwargs = parse_line(line)
            try:
                # try to call the method
                return method(*args, **kwargs)
            except TypeError as e:
                # if something went wrong, print the help for that method
                if self.debug:
                    traceback.print_exc()
                    print "%s: %s" % (type(e), e)
                if name != 'help':
                    return self.do_help(name)

                return self.do_help(None)

        # if no proper method with the name was found, do what cmd always does
        return cmd.Cmd.onecmd(self, s)
开发者ID:devopsconsulting,项目名称:vdt.deploy,代码行数:26,代码来源:api.py


示例12: index

    def index(self):
        try:
            report_form=order_report

            return dict(report_form=report_form, values={})
        except:
            traceback.print_exc()
开发者ID:LamCiuLoeng,项目名称:jcp,代码行数:7,代码来源:report.py


示例13: _init_list_add_on_change

    def _init_list_add_on_change(self, key, view_attr, lt_attr):
        view = self.view

        # this can end up being called *before* plugin_loaded() because
        # ST creates the ViewEventListeners *before* calling plugin_loaded()
        global _lt_settings
        if not isinstance(_lt_settings, sublime.Settings):
            try:
                _lt_settings = sublime.load_settings(
                    "LaTeXTools.sublime-settings"
                )
            except Exception:
                traceback.print_exc()

        self.v_attr_updates = view_attr
        self.lt_attr_updates = lt_attr

        for attr_name, d in self.v_attr_updates.items():
            settings_name = d["setting"]
            self.__dict__[attr_name] = get_setting(settings_name, view=view)

        for attr_name, d in self.lt_attr_updates.items():
            if attr_name in self.__dict__:
                continue
            settings_name = d["setting"]
            self.__dict__[attr_name] = _lt_settings.get(settings_name)

        _lt_settings.add_on_change(
            key, lambda: self._on_setting_change(False))
        self.view.settings().add_on_change(
            key, lambda: self._on_setting_change(True))
开发者ID:r-stein,项目名称:LaTeXTools,代码行数:31,代码来源:preview_utils.py


示例14: interpro_result

def interpro_result(interpro_submit_sequences, email, developing, script_dir):
    protein_ipr_db_domain = {}
    # this is done per 25
    for protein_name, interpro_result in iprscan_soappy.runInterpro(interpro_submit_sequences, email):					# get dict with as value protein name and as value various stuff
        ipr_domain_names = []
        protein_ipr_db_domain[protein_name] = {}

        for ipr_code in interpro_result:
            # list of ipr domain names for this protein
            if 'ipr_names' in interpro_result[ipr_code]:
                ipr_domain_names += interpro_result[ipr_code]['ipr_names']
            for database in interpro_result[ipr_code]:
                protein_ipr_db_domain[protein_name][ipr_code] = {database:interpro_result[ipr_code][database]}	 # update it with database and database specific name
                # make a separate list for PFAM domains, because these are used later
        protein_ipr_db_domain[protein_name]['ipr_domain_names'] = ipr_domain_names
        if developing:
            try:
                interpro_file = script_dir+os.sep+'interpro_results'+os.sep+fix_file_names(protein_name.split('|')[0].strip()+'_interpro.p')
                f = open( interpro_file, 'wb' )
                pickle.dump( protein_ipr_db_domain[protein_name], f )
                print 'wrote interpro data to '+interpro_file
            except:
                print traceback.print_exc()
                pass
    return protein_ipr_db_domain
开发者ID:Rassoul65,项目名称:miP3,代码行数:25,代码来源:interpro_scanner.py


示例15: loadModules

def loadModules(prefix):
    """ Return modules, errorlist, num_testmodules, suite. """

    try:
        from minds import allmodules
    except ImportError:
        traceback.print_exc()

    try:
        reload(allmodules)
    except ImportError:
        pass    # bug [856103] (https://sourceforge.net/tracker/?func=detail&atid=105470&aid=856103&group_id=5470)

    modules = []
    errorlist = []
    suite = unittest.TestSuite()
    num_testmodules = 0

    for (package, name) in allmodules.modules:
        package_name = '%s.%s' % (package, name)
        try:
            mod = __import__(package_name, globals(), locals(), [name])
        except Exception, e:
            buf = StringIO.StringIO()
            traceback.print_exc(file=buf)
            errorlist.append(buf.getvalue())
            continue

        modules.append(mod)
        module_suite = loadTestCases(mod, prefix)
        if module_suite:
            num_testmodules += 1
            suite.addTest(module_suite)
开发者ID:BackupTheBerlios,项目名称:mindretrieve-svn,代码行数:33,代码来源:san_test.py


示例16: tearDown

    def tearDown(self):
        try:
            if not hasattr(self, 'stderr'):
                self.unhook_stderr()
            if hasattr(self, 'stderr'):
                sys.__stderr__.write(self.stderr)
        except:
            traceback.print_exc()
        if hasattr(self, '_timer'):
            self._timer.cancel()
            hub = gevent.hub.get_hub()
            if self._switch_count is not None and hasattr(hub, 'switch_count'):
                msg = ''
                if hub.switch_count < self._switch_count:
                    msg = 'hub.switch_count decreased?\n'
                elif hub.switch_count == self._switch_count:
                    if self.switch_expected:
                        msg = '%s.%s did not switch\n' % (type(self).__name__, self.testname)
                elif hub.switch_count > self._switch_count:
                    if not self.switch_expected:
                        msg = '%s.%s switched but expected not to\n' % (type(self).__name__, self.testname)
                if msg:
                    print >> sys.stderr, 'WARNING: ' + msg

            if hasattr(gevent.core, '_event_count'):
                event_count = (gevent.core._event_count(), gevent.core._event_count_active())
                if event_count > self._event_count:
                    args = (type(self).__name__, self.testname, self._event_count, event_count)
                    sys.stderr.write('WARNING: %s.%s event count was %s, now %s\n' % args)
                    gevent.sleep(0.1)
        else:
            sys.stderr.write('WARNING: %s.setUp does not call base class setUp\n' % (type(self).__name__, ))
开发者ID:ailling,项目名称:gevent-websocket,代码行数:32,代码来源:greentest.py


示例17: __get_module_from_str

    def __get_module_from_str(self, modname, print_exception, pyfile):
        """ Import the module in the given import path.
            * Returns the "final" module, so importing "coilib40.subject.visu"
            returns the "visu" module, not the "coilib40" as returned by __import__ """
        try:
            mod = __import__(modname)
            for part in modname.split('.')[1:]:
                mod = getattr(mod, part)
            return mod
        except:
            if print_exception:
                import pydev_runfiles_xml_rpc
                import pydevd_io
                buf_err = pydevd_io.StartRedirect(keep_original_redirection=True, std='stderr')
                buf_out = pydevd_io.StartRedirect(keep_original_redirection=True, std='stdout')
                try:
                    import traceback;traceback.print_exc()
                    sys.stderr.write('ERROR: Module: %s could not be imported (file: %s).\n' % (modname, pyfile))
                finally:
                    pydevd_io.EndRedirect('stderr')
                    pydevd_io.EndRedirect('stdout')

                pydev_runfiles_xml_rpc.notifyTest(
                    'error', buf_out.getvalue(), buf_err.getvalue(), pyfile, modname, 0)

            return None
开发者ID:apaku,项目名称:Pydev,代码行数:26,代码来源:pydev_runfiles.py


示例18: deploy

def deploy():
    assert isinstance(application.options, OptionsCore), 'Invalid application options %s' % application.options
    if not application.options.start: return
    try:
        if not os.path.isfile(application.options.configurationPath):
            print('The configuration file "%s" doesn\'t exist, create one by running the the application '
                  'with "-dump" option' % application.options.configurationPath, file=sys.stderr)
            sys.exit(1)
        with open(application.options.configurationPath, 'r') as f: config = load(f)

        assembly = application.assembly = ioc.open(aop.modulesIn('__setup__.**'), config=config)
        assert isinstance(assembly, Assembly), 'Invalid assembly %s' % assembly
        
        import logging
        logging.basicConfig(format=format())
        for name in warning_for(): logging.getLogger(name).setLevel(logging.WARN)
        for name in info_for(): logging.getLogger(name).setLevel(logging.INFO)
        for name in debug_for(): logging.getLogger(name).setLevel(logging.DEBUG)
        
        try: assembly.processStart()
        finally: ioc.deactivate()
    except SystemExit: raise
    except (SetupError, ConfigError):
        print('-' * 150, file=sys.stderr)
        print('A setup or configuration error occurred while deploying, try to rebuild the application properties by '
              'running the the application with "configure components" options', file=sys.stderr)
        traceback.print_exc(file=sys.stderr)
        print('-' * 150, file=sys.stderr)
    except:
        print('-' * 150, file=sys.stderr)
        print('A problem occurred while deploying', file=sys.stderr)
        traceback.print_exc(file=sys.stderr)
        print('-' * 150, file=sys.stderr)
开发者ID:adityaathalye,项目名称:Ally-Py,代码行数:33,代码来源:deploy.py


示例19: get_data_from_url

def get_data_from_url(url, num_tries=5):
    tries = 0
    while True:
        try:
            u = urllib2.urlopen(url)
            result = u.read()
            u.close()
            if result:
                data = json.loads(result)
                return data
            return None
        except:
            tries += 1
            if tries == num_tries:
                break

            wait = 2 ** (tries + 1)
            error = 'Exception for {url}. Sleeping for {wait} secs'.format(
                    url=url, wait=wait)
            errors.append(error)
            print error
            traceback.print_exc(file=sys.stdout)
            time.sleep(wait)

    return None
开发者ID:GautamGupta,项目名称:rmc,代码行数:25,代码来源:crawler.py


示例20: dump

def dump():
    assert isinstance(application.options, OptionsCore), 'Invalid application options %s' % application.options
    if not application.options.writeConfigurations: return
    if not __debug__:
        print('Cannot dump configuration file if python is run with "-O" or "-OO" option', file=sys.stderr)
        sys.exit(1)
    configFile = application.options.configurationPath
    try:
        if os.path.isfile(configFile):
            with open(configFile, 'r') as f: config = load(f)
        else: config = {}
        
        assembly = application.assembly = ioc.open(aop.modulesIn('__setup__.**'), config=config)
        assert isinstance(assembly, Assembly), 'Invalid assembly %s' % assembly
        try:
            if os.path.isfile(configFile): os.rename(configFile, configFile + '.bak')
            for config in assembly.configurations: assembly.processForName(config)
            # Forcing the processing of all configurations
            with open(configFile, 'w') as f: save(assembly.trimmedConfigurations(), f)
            print('Created "%s" configuration file' % configFile)
        finally: ioc.deactivate()
    except SystemExit: raise
    except:
        print('-' * 150, file=sys.stderr)
        print('A problem occurred while dumping configurations', file=sys.stderr)
        traceback.print_exc(file=sys.stderr)
        print('-' * 150, file=sys.stderr)
开发者ID:adityaathalye,项目名称:Ally-Py,代码行数:27,代码来源:deploy.py



注:本文中的traceback.print_exc函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python traceback.print_exception函数代码示例发布时间:2022-05-27
下一篇:
Python traceback.format_tb函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap