本文整理汇总了Python中traceback.format_exc函数的典型用法代码示例。如果您正苦于以下问题:Python format_exc函数的具体用法?Python format_exc怎么用?Python format_exc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_exc函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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
示例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)
示例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())
示例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())
示例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
示例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)
示例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
示例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)
示例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/")
示例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()))
示例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
示例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
示例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