本文整理汇总了Python中traceback.tb_lineno函数的典型用法代码示例。如果您正苦于以下问题:Python tb_lineno函数的具体用法?Python tb_lineno怎么用?Python tb_lineno使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tb_lineno函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_error_info
def get_error_info(self, indent_level , section_name):
return_str_arr = [""]
return_str = ""
return_str_arr.append(self.get_indent_chars(indent_level))
return_str_arr.append("<error>")
return_str_arr.append(self.get_indent_chars(indent_level))
return_str_arr.append("<" + section_name + ">")
error_type, error_value, tb = sys.exc_info()
print "error_type:"
print error_type, type(error_type)
print "error_value:"
print error_value, type(error_value)
print "line:"
print traceback.tb_lineno(tb)
print "error (filename, line number, function, statement, value):"
print traceback.extract_tb(tb)
# print "message:"
# print error_value.message
print "-----------------------------------------"
return_str_arr.append(self.get_indent_chars(indent_level))
return_str_arr.append("</" + section_name + ">")
return_str_arr.append(self.get_indent_chars(indent_level))
return_str_arr.append("</error>")
return_str = "".join(return_str_arr)
return return_str
示例2: velo_save_file
def velo_save_file(request):
if request.method == 'POST':
try:
incomming_file = json.loads(request.body)
remote_path = incomming_file['remote_path']
filename = incomming_file['filename']
text = incomming_file['text']
site_user = 'acmetest'
velo_user = 'acmetest'
velo_pass = 'acmetest'
process = Popen(
['python', './apps/velo/save_file.py', text, local_path, remote_path, site_user, velo_user, velo_pass, filename], stdout=PIPE)
(out, err) = process.communicate()
exit_code = process.wait()
out = out.splitlines(True)[1:]
print out
if exit_code == 0:
return HttpResponse(status=200)
else:
return HttpResponse(status=500)
except Exception as e:
import traceback
print '1', e.__doc__
print '2', sys.exc_info()
print '3', sys.exc_info()[0]
print '4', sys.exc_info()[1]
print '5', traceback.tb_lineno(sys.exc_info()[2])
ex_type, ex, tb = sys.exc_info()
print '6', traceback.print_tb(tb)
return HttpResponse(status=500)
else:
return HttpResponse(status=404)
示例3: better_exec
def better_exec(code, context, text, realfile = "<code>"):
"""
Similiar to better_compile, better_exec will
print the lines that are responsible for the
error.
"""
import bb.parse
if not hasattr(code, "co_filename"):
code = better_compile(code, realfile, realfile)
try:
exec(code, _context, context)
except Exception:
(t, value, tb) = sys.exc_info()
if t in [bb.parse.SkipPackage, bb.build.FuncFailed]:
raise
logger.exception("Error executing python function in '%s'", code.co_filename)
# Strip 'us' from the stack (better_exec call)
tb = tb.tb_next
import traceback
tbextract = traceback.extract_tb(tb)
tbextract = "\n".join(traceback.format_list(tbextract))
bb.msg.error(bb.msg.domain.Util, "Traceback:")
for line in tbextract.split('\n'):
bb.msg.error(bb.msg.domain.Util, line)
line = traceback.tb_lineno(tb)
bb.msg.error(bb.msg.domain.Util, "The lines leading to this error were:")
_print_trace( text.split('\n'), line )
raise
示例4: save_layout
def save_layout(request):
print 'got a save request'
if request.method == 'POST':
try:
data = json.loads(request.body)
if len(TileLayout.objects.filter(layout_name=data['name'])) == 0:
if data['default_layout'] == 1:
print 'got a new default'
isDefault = TileLayout.objects.filter(
user_name=request.user, default=1)
if isDefault:
for i in isDefault:
print 'found old default named ' + i.layout_name
i.default = 0
i.save()
layout = TileLayout(user_name=request.user, layout_name=data['name'], board_layout=json.dumps(
data['layout']), mode=data['mode'], default=data['default_layout'])
layout.save()
return HttpResponse(status=200)
else:
return HttpResponse(status=422)
except Exception as e:
import traceback
print '1', e.__doc__
print '2', sys.exc_info()
print '3', sys.exc_info()[0]
print '4', sys.exc_info()[1]
print '5', traceback.tb_lineno(sys.exc_info()[2])
ex_type, ex, tb = sys.exc_info()
print '6', traceback.print_tb(tb)
return HttpResponse(status=500)
示例5: onError
def onError():
et, ev, tb = sys.exc_info()
t = time()
red = "\x1b\x5b1;31;40m"
regular= "\x1b\x5b0;37;40m"
print "========="+red+"ERROR"+regular+"========"
print "Time :",t
last = []
skipped= 0
while tb :
co = tb.tb_frame.f_code
filename = str(co.co_filename)
line_no = str(traceback.tb_lineno(tb))
tb = tb.tb_next
if last!=[filename,line_no]:
if skipped!=0:
print "... Skipped",skipped,"repeat(s)."
print "File :",filename
print "Line :",line_no
print "------"
last=[filename,line_no]
skipped = 0
else:
skipped += 1
if skipped!=0:
print "... Skipped",skipped,"repeats(s)."
print "Error:", ev
print "======================="
pass
示例6: get_folder
def get_folder(request):
if request.method == 'POST':
folder = json.loads(request.body)
try:
print 'getting folder from velo ', folder['file']
process = Popen(
['python', './apps/velo/get_folder.py', folder['file']], stdout=PIPE)
(out, err) = process.communicate()
exit_code = process.wait()
out = out.splitlines(False)
out[0] = folder['file']
return HttpResponse(json.dumps(out))
except Exception as e:
import traceback
print '1', e.__doc__
print '2', sys.exc_info()
print '3', sys.exc_info()[0]
print '4', sys.exc_info()[1]
print '5', traceback.tb_lineno(sys.exc_info()[2])
ex_type, ex, tb = sys.exc_info()
print '6', traceback.print_tb(tb)
return HttpResponse(status=500)
else:
return HttpResponse(status=404)
示例7: SvcDoRun
def SvcDoRun(self):
self.log("SSDUT " + "Run")
self.log("SSDUT " + "sys.arg" + sys.argv[0])
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
try:
sys.WORK_DIR = "SSDUT_NEWS"
sys.PORT = 8000
cwd = os.path.join(os.environ['LOCALAPPDATA'], sys.WORK_DIR)
try:
os.mkdir(cwd)
except Exception as e:
pass
os.chdir(cwd)
self.log("SSDUT cwd" + cwd)
self.log("SSDUT work place" + os.getcwd())
import newsUpdater
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
newsUpdater.main()
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
except Exception as e:
self.log('Exception: %s' % e)
self.log('line %d' % traceback.tb_lineno(sys.exc_info()[2]))
self.SvcStop()
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
示例8: run
def run(self, input=None):
#self.printCmd()
s_out = ""
s_err = ""
try:
proc = subprocess.Popen(self.cmd,\
stdin=subprocess.PIPE,\
stdout=subprocess.PIPE,\
stderr=subprocess.PIPE)
if input != None:
(s_out,s_err) = proc.communicate(input)
else:
(s_out,s_err) = proc.communicate()
proc.wait()
##(s_out,s_err) = proc.communicate()
except Exception as e:
e_type, e_value, e_trace = sys.exc_info()
print("Exception: " + str(e))
print("\tType: " + str(e_type))
print("\tLine #: " + str(traceback.tb_lineno(e_trace)))
return (s_out,s_err,-1)
if proc.returncode != 0:
print("Error executing the test: " + ' '.join(self.cmd))
print("Return Value: " + str(proc.returncode))
print("If the script doesn't stop this was likely an intentional error")
return (s_out,s_err, proc.returncode)
status = 0
if ( self.depends ):
(s_out, s_err, status) = self.depends.run(s_out)
return (s_out, s_err,status)
示例9: returnError
def returnError(handler, message, level="INFO"):
reqPath = handler.request.path
reqBody = handler.request.body
logMesg = message + " (" + reqPath + " " + reqBody + ")"
if level == "INFO":
logging.info(logMesg)
elif level == "WARNING":
logging.warning(logMesg)
elif level == "ERROR":
logMesgDetail = ""
et, ev, tb = sys.exc_info()
logMesgDetail += str(et) + " "
logMesgDetail += str(ev) + " "
while tb:
co = tb.tb_frame.f_code
line_no = "#" + str(traceback.tb_lineno(tb)) + " "
logMesgDetail += line_no
tb = tb.tb_next
logging.error(logMesg + " " + logMesgDetail)
mail.send_mail(sender = "[email protected]",
to = "[email protected]",
subject = "Melbourne Journey ERROR",
body = logMesg + " " + logMesgDetail)
finalResults = []
finalResults.append({'status': "WORQ-ERROR", 'message': message})
handler.response.out.write(simplejson.dumps(finalResults))
示例10: node_info
def node_info(request):
if request.method == 'POST':
''' For demo purposes this is loading a local file '''
try:
from xml.etree.ElementTree import parse
tree = parse('scripts/registration.xml')
root = tree.getroot()
name = json.loads(request.body)['node']
response = {}
for node in root:
if node.attrib['shortName'] == name:
response['org'] = node.attrib['organization']
response['namespace'] = node.attrib['namespace']
response['email'] = node.attrib['supportEmail']
response['ip'] = node.attrib['ip']
response['longName'] = node.attrib['longName']
response['version'] = node.attrib['version']
response['shortName'] = name
response['adminPeer'] = node.attrib['adminPeer']
response['hostname'] = node.attrib['hostname']
for child in list(node):
if child.tag[-len('AuthorizationService'):] == "AuthorizationService":
response['authService'] = child.attrib["endpoint"]
if child.tag[-len('GeoLocation'):] == "GeoLocation":
response['location'] = child.attrib["city"]
if child.tag[-len('Metrics'):] == "Metrics":
for gchild in list(child):
if gchild.tag[-len('DownloadedData'):] == "DownloadedData":
response['dataDownCount'] = gchild.attrib['count']
response['dataDownSize'] = gchild.attrib['size']
response['dataDownUsers'] = gchild.attrib['users']
if gchild.tag[-len('RegisteredUsers'):] == "RegisteredUsers":
response['registeredUsers'] = gchild.attrib['count']
from pyesgf.search import SearchConnection
print 'attempting to connect to ' + 'http://' + response['hostname'] + 'esg-search/'
conn = SearchConnection('http://' + response['hostname'] + '/esg-search/', distrib=True)
try:
conn.get_shard_list()
response['status'] = 'up'
except Exception as e:
print repr(e)
response['status'] = 'down'
return HttpResponse(json.dumps(response))
except Exception as e:
import traceback
print '1', e.__doc__
print '2', sys.exc_info()
print '3', sys.exc_info()[0]
print '4', sys.exc_info()[1]
print '5', traceback.tb_lineno(sys.exc_info()[2])
ex_type, ex, tb = sys.exc_info()
print '6', traceback.print_tb(tb)
return HttpResponse(status=500)
elif request.method == 'POST':
print "Unexpected POST request"
return HttpResponse(status=500)
示例11: getExceptionInfo
def getExceptionInfo(self,tb):
import traceback
txtStack = []
lineno = 0
while (tb is not None):
f = tb.tb_frame
lineno = traceback.tb_lineno(tb)
co = f.f_code
filename = co.co_filename
name = co.co_name
tb = tb.tb_next
txtStack.append( (filename,lineno,name) )
return txtStack
示例12: better_exec
def better_exec(code, context, text, realfile):
"""
Similiar to better_compile, better_exec will
print the lines that are responsible for the
error.
"""
import bb,sys
try:
exec code in context
except:
(t,value,tb) = sys.exc_info()
if t in [bb.parse.SkipPackage, bb.build.FuncFailed]:
raise
# print the Header of the Error Message
bb.msg.error(bb.msg.domain.Util, "Error in executing: ", realfile)
bb.msg.error(bb.msg.domain.Util, "Exception:%s Message:%s" % (t,value) )
# let us find the line number now
while tb.tb_next:
tb = tb.tb_next
import traceback
line = traceback.tb_lineno(tb)
_print_trace( text.split('\n'), line )
raise
示例13: report_spam_to_cloudflare
def report_spam_to_cloudflare(modeladmin, request, queryset):
"Reports selected comments as spam to CloudFlare."
def stringify_params(params):
"Converts a dictionary of query params into a URL-encoded string."
return '&'.join(['%s=%s' % (urllib.quote(k), urllib.quote(v)) for k, v in params.items()])
def get_comment_details(comment):
"Constructs dictionary of comment details to be reported."
return {
'a': comment.name,
'am': comment.user_email,
'ip': comment.ip_address,
'con': comment.comment[:100]
}
def report_spam_incident(comment_info):
"Sends spam incident to CloudFlare over HTTPS."
cf_url = 'https://www.cloudflare.com/ajax/external-event.html'
cf_event = 'CF_USER_SPAM'
cf_token = settings.CLOUDFLARE_API_KEY
cf_email = settings.CLOUDFLARE_EMAIL
request_params = {
'u': cf_email,
'tkn': cf_token,
'evnt_t': cf_event,
'evnt_v': json.dumps(comment_info)
}
request_url = '%s?%s' % (cf_url, stringify_params(request_params))
http = httplib2.Http(disable_ssl_certificate_validation=True)
response = json.loads(http.request(request_url)[1])
if response['result'] == 'success':
logger.info('CloudFlare // Reported spammer: %s %s' % (comment_info['am'], comment_info['ip']))
return True
else:
logger.warning('CloudFlare // Failed to report spammer: %s' % (response['msg']))
return False
try:
reported = []
for obj in queryset:
comment_info = get_comment_details(obj)
successful = report_spam_incident(comment_info)
if successful:
reported.append(str(obj.id))
modeladmin.message_user(request, '%s spam comment(s) reported to CloudFlare: %s' % (len(reported), ', '.join(reported)))
unreported = [str(obj.id) for obj in queryset if str(obj.id) not in reported]
if unreported:
logger.warning('CloudFlare // Did not report comments: %s' % (', '.join(unreported)))
except:
logger.error("Error on line " + str(traceback.tb_lineno(sys.exc_info()[2])) + ": " + str(sys.exc_info()[1]) + ": " + str(sys.exc_info()[0]))
modeladmin.message_user(request, 'Could not report spam to CloudFlare.')
示例14: __call__
def __call__(self, target):
try:
self.prepare(target)
satisfied = self.evaluate(target)
except KeyboardInterrupt:
raise
except:
display_error = self.pars.verbose_level > 0 or self.pars.debug
if display_error:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
print("******************************************")
print("Problem evaluating feature:" + self.name)
print(" %s %s" % (exceptionType, exceptionValue))
for line in traceback.format_exc().splitlines()[-12:-1]:
print(" " + line)
print(" originally on line:%d" % traceback.tb_lineno(exceptionTraceback))
if self.pars.debug: #and self.pars.verbose_level > 1:
raise
else:
print("(Proceeding as 'unsatisfied')\n")
satisfied = False
if hasattr(self, 'metric'):
self.metric.results = self.pars.penalty * \
npy.ones((self.metric_len,), float)
for sf in self.subfeatures:
if hasattr(sf, 'metric'):
sf.metric.results = self.pars.penalty * \
npy.ones((sf.metric_len,), float)
if satisfied:
self.finish(target)
self.results.satisfied = satisfied
return satisfied
示例15: unhandled_exception_hook
def unhandled_exception_hook(errtype, value, tb):
"""Handle gammu errors separately."""
gammu_names=dir(gammu)
for gammu_name in gammu_names:
if 'ERR'==gammu_name[:3]:
#print errtype.__name__, gammu_name
if gammu_name==errtype.__name__:
#print value
#main()
print 'Gammu %s: %s' % (value[0]['Where'],value[0]['Text'])
try:
main()
except:
pass
if errtype==KeyboardInterrupt:
print 'Goodbye!'
sys.exit(0)
elif errtype==MemoryError:
print 'Running our of memory!'
print value
print tb
elif errtype==SystemExit:
pass
#Take away potential pidfile if we are daemon.
else:
print 'Unhandled error:', errtype, value , traceback.tb_lineno(tb)
sys.exit(1)