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

Python traceback.format_exc函数代码示例

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

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



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

示例1: process

def process(service_name):
    try:
        print service_name
        jsonData = json.loads(request.data)
        print request.data
        action = jsonData["action"]
        isAllow = False
        for item in utils.config.ALLOW_SERVICE.split(','):
            if service_name == item:
                isAllow = True
        if service_name is None or service_name == '' or not isAllow:
            return 'No such Service'

        result = ''

        if action == 'ACTION_SERVICE_CREATE':
            result = service.serverService.action_service_create(service_name, jsonData)
        elif action == 'ACTION_SERVICE_UPDATE':
            result = service.serverService.action_service_update(service_name, jsonData)
        elif action == 'ACTION_CLIENT_SERVICE_CREATE':
            result = service.serverService.action_client_service_create(service_name, jsonData)
        elif action == 'ACTION_SERVICE_FOLLOWED_CHANGE':
            result = service.serverService.action_service_followed_change(service_name, jsonData)
        elif action == 'ACTION_SERVICE_DING':
            result = service.serverService.action_service_ding(action, jsonData)


    except Exception, e:
        logging.error(e)
        print traceback.format_exc()
        result.code = "1001"
        result.message = "unknow Exception"
        resp = Response(result.get_json())
        return resp
开发者ID:chenyueling,项目名称:python_lofter,代码行数:34,代码来源:ding-factory.py


示例2: _listenEvent

	def _listenEvent(self):	
		currentEvent = self._newEvent()
		self._loop=True
		btnclick=False
		try:
			while self._loop==True:
				r,w,x = select([self._dev], [], [])
				for event in self._dev.read():
					if event.type==3:
						if event.code==0:
							currentEvent['x']=event.value
						elif event.code==1:
							currentEvent['y']=event.value

						elif event.code==24:
							currentEvent['pression']=event.value
					elif event.type==1:
						if event.code==330:
							btnclick=True


					complete=btnclick
					for (key,ev) in currentEvent.items():
						if ev==-1:
							complete=False
					if complete:
						(currentEvent['x'],currentEvent['y'])=self.calculateCoord(currentEvent['x'],currentEvent['y'])
						if self._blocking:
							return currentEvent
						self._callback(self,currentEvent)
						currentEvent = self._newEvent()
		except:
			print traceback.format_exc()
			return
开发者ID:air01a,项目名称:pitft,代码行数:34,代码来源:mouse.py


示例3: log_project_issue

    def log_project_issue(self,filepath,filename,problem="",detail="",desc=None,opens_with=None):
        cursor = self.conn.cursor()

        matches=re.search(u'(\.[^\.]+)$',filename)
        file_xtn = ""
        if matches is not None:
            file_xtn=str(matches.group(1))
        else:
            raise ArgumentError("Filename %s does not appear to have a file extension" % filename)

        typenum=self.project_type_for_extension(file_xtn,desc=desc,opens_with=opens_with)

        try:
            cursor.execute("""insert into edit_projects (filename,filepath,type,problem,problem_detail,lastseen,valid)
            values (%s,%s,%s,%s,%s,now(),false) returning id""", (filename,filepath,typenum,problem,detail))
        except psycopg2.IntegrityError as e:
            print str(e)
            print traceback.format_exc()
            self.conn.rollback()
            cursor.execute("""update edit_projects set lastseen=now(), valid=false, problem=%s, problem_detail=%s where filename=%s and filepath=%s returning id""", (problem,detail,filename,filepath))
        #print cursor.mogrify("""update edit_projects set lastseen=now(), valid=false, problem=%s, problem_detail=%s where filename=%s and filepath=%s returning id""", (problem,detail,filename,filepath))
        result=cursor.fetchone()
        id = result[0]
        self.conn.commit()
        return id
开发者ID:guardian,项目名称:assetsweeper,代码行数:25,代码来源:database.py


示例4: _execute_jobs

    def _execute_jobs(self):

        logger.info('Jobs execution started')
        try:
            logger.debug('Lock acquiring')
            with sync_manager.lock(self.JOBS_LOCK, blocking=False):
                logger.debug('Lock acquired')

                ready_jobs = self._ready_jobs()

                for job in ready_jobs:
                    try:
                        self.__process_job(job)
                        job.save()
                    except LockError:
                        pass
                    except Exception as e:
                        logger.error('Failed to process job {0}: '
                            '{1}\n{2}'.format(job.id, e, traceback.format_exc()))
                        continue

        except LockFailedError as e:
            pass
        except Exception as e:
            logger.error('Failed to process existing jobs: {0}\n{1}'.format(
                e, traceback.format_exc()))
        finally:
            logger.info('Jobs execution finished')
            self.__tq.add_task_at(self.JOBS_EXECUTE,
                self.jobs_timer.next(),
                self._execute_jobs)
开发者ID:agodin,项目名称:mastermind,代码行数:31,代码来源:__init__.py


示例5: datastream_updated

 def datastream_updated(self, botengine, address, content):
     """
     Data Stream Updated
     :param botengine: BotEngine environment
     :param address: Data Stream address
     :param content: Data Stream content
     """
     for intelligence_id in self.intelligence_modules:
         try:
             self.intelligence_modules[intelligence_id].datastream_updated(botengine, address, content)
         except Exception as e:
             botengine.get_logger().warn("location.py - Error delivering datastream message to location microservice (continuing execution): " + str(e))
             import traceback
             botengine.get_logger().error(traceback.format_exc())
     
     # Device intelligence modules
     for device_id in self.devices:
         if hasattr(self.devices[device_id], "intelligence_modules"):
             for intelligence_id in self.devices[device_id].intelligence_modules:
                 try:
                     self.devices[device_id].intelligence_modules[intelligence_id].datastream_updated(botengine, address, content)
                 except Exception as e:
                     botengine.get_logger().warn("location.py - Error delivering datastream message to device microservice (continuing execution): " + str(e))
                     import traceback
                     botengine.get_logger().error(traceback.format_exc())
开发者ID:peoplepower,项目名称:composer-sdk-python,代码行数:25,代码来源:location.py


示例6: _RegisterDebuggee

  def _RegisterDebuggee(self, service):
    """Single attempt to register the debuggee.

    If the registration succeeds, sets self._debuggee_id to the registered
    debuggee ID.

    Args:
      service: client to use for API calls

    Returns:
      (registration_required, delay) tuple
    """
    try:
      request = {'debuggee': self._GetDebuggee()}

      try:
        response = service.debuggees().register(body=request).execute()

        self._debuggee_id = response['debuggee']['id']
        native.LogInfo('Debuggee registered successfully, ID: %s' % (
            self._debuggee_id))
        self.register_backoff.Succeeded()
        return (False, 0)  # Proceed immediately to list active breakpoints.
      except BaseException:
        native.LogInfo('Failed to register debuggee: %s, %s' %
                       (request, traceback.format_exc()))
    except BaseException:
      native.LogWarning('Debuggee information not available: ' +
                        traceback.format_exc())

    return (True, self.register_backoff.Failed())
开发者ID:GoogleCloudPlatform,项目名称:cloud-debug-python,代码行数:31,代码来源:gcp_hub_client.py


示例7: tokenize

def tokenize(n, tagsDict):
	cleaner = Cleaner()
	cleaner.javascript = True
	cleaner.style = True
	i = 0
	df = pandas.DataFrame(columns=[list(tagsDict)])

	while (i < n):
		allVector = {}
		if (os.path.isfile("spam/%d.txt" % i)):
			try:
				for word in tagsDict:
					allVector[word] = 0
				readInFile = open("spam/%d.txt" % i)
				content = readInFile.read()
				noSymbols = re.sub('[^A-Za-z-]+', ' ', content.lower())  # noSymbols is stripped of symbols
				allCopy = noSymbols.split()  # allCopy is the set of words without symbols
				for tag in allCopy:
					df.ix[i[tag]] = df.ix[i[tag]]  + 1
				df.ix[i['isSpam']] = 'spam'
				
			except Exception, err:
				print traceback.format_exc()
    			print sys.exc_info()[0]
		
		i = i + 1		
开发者ID:0x0mar,项目名称:Fishing-for-Phishing,代码行数:26,代码来源:tokenizer2.py


示例8: new_f

 def new_f(request, *args, **kwargs):
   try:
     return f(request, *args, **kwargs)
   except self.Exception, ex:
     if request.ResponseType == 'json':
       if self.showStackTrace:
         return '''{message:"%s", stackTrace:"%s"}'''%(str(ex)+'\n'+traceback.format_exc())
       else:
         return '''{message:%s}'''%(self.message)
     elif request.ResponseType == 'xml':
       if self.showStackTrace:
         return '''<root><message>%s</message><stackTrace>%s</stackTrace></root>"'''%(str(ex)+'\n'+traceback.format_exc())
       else:
         return '''<root><message>%s</message></root>'''%(self.message)
     else:
       if request.status == None:
         request.status = self.message or ''
       else:
         request.status += self.message or ''
       logging.error(str(ex)+'\n'+traceback.format_exc())
       if self.showStackTrace or DEBUG:
         request.status+= "  Details:<br/>"+ex.__str__()+'</br>'+traceback.format_exc()
       else:
         'There has been some problem, and the moderator was informed about it.'
       request.redirect(self.redirectUrl)
开发者ID:Halicea,项目名称:HalWebSite,代码行数:25,代码来源:decorators.py


示例9: display

def display():
    global timer, alert, fps
    try:
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        begin = time.time()
        glUseProgram(shader)

        nextAnimation()

        red = [1.0, 0., 0., 1.]
        green = [0., 1.0, 0., 1.]
        blue = [0., 0., 1.0, 1.]

        glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,blue)
        drawSkyBox((N - 32) / 2, (32 - N) / 2, 32, 16)
        glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,red)
        drawPlane(64, 64)
        glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,green)
        drawWalls()

        glutSwapBuffers()
        elapsed = time.time() - begin
        fps = 1. / elapsed
    except Exception as e:
        print 'error occurs:', e
        print traceback.format_exc()
        glutLeaveMainLoop()
    return
开发者ID:amalrkrishna,项目名称:virtualnav-mpu6050,代码行数:28,代码来源:maze.py


示例10: _shutdown

  def _shutdown(self, status_result):
    runner_status = self._runner.status

    try:
      propagate_deadline(self._chained_checker.stop, timeout=self.STOP_TIMEOUT)
    except Timeout:
      log.error('Failed to stop all checkers within deadline.')
    except Exception:
      log.error('Failed to stop health checkers:')
      log.error(traceback.format_exc())

    try:
      propagate_deadline(self._runner.stop, timeout=self.STOP_TIMEOUT)
    except Timeout:
      log.error('Failed to stop runner within deadline.')
    except Exception:
      log.error('Failed to stop runner:')
      log.error(traceback.format_exc())

    # If the runner was alive when _shutdown was called, defer to the status_result,
    # otherwise the runner's terminal state is the preferred state.
    exit_status = runner_status or status_result

    self.send_update(
        self._driver,
        self._task_id,
        exit_status.status,
        status_result.reason)

    self.terminated.set()
    defer(self._driver.stop, delay=self.PERSISTENCE_WAIT)
开发者ID:caofangkun,项目名称:apache-aurora,代码行数:31,代码来源:aurora_executor.py


示例11: post

    def post(self, request):
        try:
            params = request.POST
            action = params.get("action", "deploy")
            stage = params.get("current_stage")
            ngapp2_deploy_utils = Ngapp2DeployUtils()
            if action == "cancel":
                if stage == "deploy_to_canary":
                    ngapp2_deploy_utils.rollback_canary()
                elif stage == "deploy_to_prod":
                    ngapp2_deploy_utils.rollback_prod()

                ngapp2_deploy_utils.set_status_to_zk("SERVING_BUILD")
            else:
                if stage == 'pre_deploy':
                    self.start_pre_deploy(request)
                elif stage == 'post_deploy':
                    self.start_post_deploy(request)
                elif stage == 'rollback':
                    self.start_roll_back(request)

                ngapp2_deploy_utils.set_status_to_zk(stage)
        except:
            logger.error(traceback.format_exc())
            logger.warning(traceback.format_exc())
        finally:
            return redirect("/ngapp2/deploy/")
开发者ID:chaunceyhan,项目名称:teletraan,代码行数:27,代码来源:ngapp2_view.py


示例12: _run_job

    def _run_job(cls, job_id, additional_job_params):
        """Starts the job."""
        logging.info(
            'Job %s started at %s' %
            (job_id, utils.get_current_time_in_millisecs()))
        cls.register_start(job_id)

        try:
            result = cls._run(additional_job_params)
        except Exception as e:
            logging.error(traceback.format_exc())
            logging.error(
                'Job %s failed at %s' %
                (job_id, utils.get_current_time_in_millisecs()))
            cls.register_failure(
                job_id, '%s\n%s' % (unicode(e), traceback.format_exc()))
            raise taskqueue_services.PermanentTaskFailure(
                'Task failed: %s\n%s' % (unicode(e), traceback.format_exc()))

        # Note that the job may have been canceled after it started and before
        # it reached this stage. This will result in an exception when the
        # validity of the status code transition is checked.
        cls.register_completion(job_id, result)
        logging.info(
            'Job %s completed at %s' %
            (job_id, utils.get_current_time_in_millisecs()))
开发者ID:VictoriaRoux,项目名称:oppia,代码行数:26,代码来源:jobs.py


示例13: nextMonthDay

def nextMonthDay(cnt, now, start_time, config):
	months = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
	days = config['day'].split(",")
	next = None
	try:
		for month in months:
			if cnt == 0 and int(month) < int(start_time.month): # same year
				continue
			for day in days:
				if cnt == 0 and int(month) == int(start_time.month) and int(day) < int(start_time.day):
					continue	
				try:
					next = datetime.datetime(start_time.year + cnt, int(month), int(day), start_time.hour, start_time.minute, 0)
					cronlog("update monthly::(name, next, previous, current) = (%s, %s, %s, %s)"%(config['name'], str(next), str(start_time), str(now)))
					if next >= start_time:
						if next > now:
							return next
						else:
							next = None
				except:
					pass
	except:
		cronlog("update monthly::exception = %s"%(traceback.format_exc()))
		print traceback.format_exc()
	return next
开发者ID:gsrr,项目名称:IFT_jerry,代码行数:25,代码来源:iftcron.py


示例14: xonshrc_context

def xonshrc_context(rcfiles=None, execer=None, initial=None):
    """Attempts to read in xonshrc file, and return the contents."""
    loaded = builtins.__xonsh_env__["LOADED_RC_FILES"] = []
    if initial is None:
        env = {}
    else:
        env = initial
    if rcfiles is None or execer is None:
        return env
    env["XONSHRC"] = tuple(rcfiles)
    for rcfile in rcfiles:
        if not os.path.isfile(rcfile):
            loaded.append(False)
            continue
        try:
            run_script_with_cache(rcfile, execer, env)
            loaded.append(True)
        except SyntaxError as err:
            loaded.append(False)
            exc = traceback.format_exc()
            msg = "{0}\nsyntax error in xonsh run control file {1!r}: {2!s}"
            warnings.warn(msg.format(exc, rcfile, err), RuntimeWarning)
            continue
        except Exception as err:
            loaded.append(False)
            exc = traceback.format_exc()
            msg = "{0}\nerror running xonsh run control file {1!r}: {2!s}"
            warnings.warn(msg.format(exc, rcfile, err), RuntimeWarning)
            continue
    return env
开发者ID:Carreau,项目名称:xonsh,代码行数:30,代码来源:environ.py


示例15: _run

 def _run(self):
   try:
     start_time = time.time()
     comment = ''
     num_ok = 0
     num_err = 0
     num_post = 0
     loop = 0
     while True:
       
       if loop % 2:
         if self.get_page(comment):
           num_ok += 1
         else:
           num_err += 1
         #check elapsed
         elapsed = time.time() - start_time
         if elapsed > self._seconds:
           break
       else:
         comment = self.post_comment()
         num_post += 1
       
       loop += 1
     
     score = float(num_post) / elapsed * 10
     percent = float(num_ok) / float(num_ok + num_err)
     value = (score, percent, num_post)
     
   except Exception, e:
     import traceback
     print traceback.format_exc()
     value = e
开发者ID:najeira,项目名称:tuningathon3,代码行数:33,代码来源:bench.py


示例16: exec_scenario_tests

    def exec_scenario_tests(self, scenario, testcase, cmd_func):
        err_str = ""
        with cmd_func(**self.dsc_kws) as dsc:
            try:
                # setup.
                if SCE_SETUP in scenario:
                    self.exec_tests(dsc, scenario[SCE_SETUP])

                # tests.
                self.exec_tests(dsc, testcase[SCE_TEST])
            except DataStoreTestError as e:
                # ERROR
                err_str = "%s" % (e)
            except (socket.timeout, ShellCmdTimeOut):
                # sock or shell timeout.
                err_str = "%s" % (traceback.format_exc())
            finally:
                try:
                    # teardown.
                    if SCE_TEARDOWN in scenario:
                        self.exec_tests(dsc, scenario[SCE_TEARDOWN])
                except (DataStoreTestError, socket.timeout, ShellCmdTimeOut):
                    # ERROR
                    if err_str == "":
                        err_str = "%s" % (traceback.format_exc())
        return err_str
开发者ID:1514louluo,项目名称:lagopus,代码行数:26,代码来源:exec_test.py


示例17: log

def log(user_id, currentMessage):
    try:
        K = list()
        logExists = os.path.exists('../log/' + str(user_id * -1) + 'log.csv')
        fieldnames = ['name', 'text']
        if logExists:
            try:
                with open('../log/' + str(user_id * -1) + 'log.csv', 'r+') as csvfile:
                    reader = csv.DictReader(csvfile)
                    K = list(reader)
                with open('../log/' + str(user_id * -1) + 'log.csv', 'w+') as csvfile:
                    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                    writer.writeheader()
                    for x in K:
                        writer.writerow(x)
                    writer.writerow({'name': currentMessage.from_user.first_name, 'text': currentMessage.text})
            except Exception:
                pass
        else:
            file('../log/' + str(user_id * -1) + 'log.csv', 'a').close()
            with open('../log/' + str(user_id * -1) + 'log.csv', 'w+') as csvfile:
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
                writer.writerow({'name': currentMessage.from_user.first_name, 'text': currentMessage.text})
    except Exception:
        traceback.format_exc()
开发者ID:agincel,项目名称:AdamTestBot,代码行数:26,代码来源:atbMiscFunctions.py


示例18: GetDockerList

	def GetDockerList(self):
		try:
			self.conn.request("GET", "/containers/json?all=1")
			r1 = self.conn.getresponse()
		except Exception,e:
				print traceback.format_exc()
				exit()
开发者ID:c295655244,项目名称:docker_platform,代码行数:7,代码来源:monitor_old.py


示例19: buildDicts

def buildDicts(n):
	cleaner = Cleaner()
	cleaner.javascript = True
	cleaner.style = True
	i = 0 
	tagsDict = set()
	while (i < n):
		if (os.path.isfile("spam/%d.txt" % i)):
			try:
				readInFile = open("spam/%d.txt" % i)
				content = readInFile.read()
				noSymbols = re.sub('[^A-Za-z-]+', ' ', content.lower())  # noSymbols is stripped of symbols
				tags = set(noSymbols.split())  # allCopy is the set of words without symbols
				tagsDict = tagsDict.union(tags)
			except Exception, err:
				print traceback.format_exc()
				print sys.exc_info()[0]
		if (os.path.isfile("notspam/%d.txt" % i)):
			try:
				readInFile = open("notspam/%d.txt" % i)
				content = readInFile.read()
				noSymbols = re.sub('[^A-Za-z-]+', ' ', content.lower())  # noSymbols is stripped of symbols
				tags = set(noSymbols.split())  # allCopy is the set of words without symbols
				tagsDict = tagsDict.union(tags)
			except Exception, err:
				print traceback.format_exc()
				print sys.exc_info()[0]
开发者ID:0x0mar,项目名称:Fishing-for-Phishing,代码行数:27,代码来源:tokenizer2.py


示例20: run_task

 def run_task(self, **kwargs):
   Session.merge(self.task)
   self.task.start_time = datetime.utcnow()
   self.task.ident = threading.get_ident()
   self.task.status = TaskStatus.running.value
   Session.merge(self.task)
   Session.commit()
   try:
     self.run_function(**kwargs)
     self.task.log = self.log.messages
     self.task.end_time = datetime.utcnow()
     self.task.status = TaskStatus.finished.value
     self.task.result = TaskResult.success.value
     self.task = Session.merge(self.task)
     Session.commit()
   except Exception as e:
     self.task.log = self.log.messages
     self.task.tb = traceback.format_exc()
     self.task.end_time = datetime.utcnow()
     self.task.status = TaskStatus.finished.value
     self.task.result = TaskResult.fail.value
     self.task = Session.merge(self.task)
     Session.commit()
     defect = jira.defect_for_exception(
       "Background Task Error: {}".format(
         self.task.name),
       e, tb=traceback.format_exc(),
       username=self.task.username)
     self.task.defect_ticket = defect.key
     self.task = Session.merge(self.task)
     Session.commit()
   finally:
     Session.remove()
开发者ID:ariens,项目名称:lifeguard,代码行数:33,代码来源:models.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python traceback.format_exception函数代码示例发布时间:2022-05-27
下一篇:
Python traceback.extract_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