本文整理汇总了Python中traceback.print_tb函数的典型用法代码示例。如果您正苦于以下问题:Python print_tb函数的具体用法?Python print_tb怎么用?Python print_tb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了print_tb函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: server
def server(self, server_id):
''' get server associated with an id, create one if none exists
'''
try:
if server_id in self.server_dict:
server_info = self.server_dict[server_id]
return server_info['proxy']
else:
url_fmt = "tcp://127.0.0.1:%i"
rep_url = url_fmt % get_unused_ip_port()
pub_url = url_fmt % get_unused_ip_port()
out_url = url_fmt % get_unused_ip_port()
DEBUG("%s \n\t RPC on %s \n\t pub on %s \n\t out on %s"
% (server_id, rep_url, pub_url, out_url))
server = ZMQServer.spawn_server(self.classpath, rep_url,
pub_url, out_url)
proxy = ZMQ_RPC(rep_url)
self.server_dict[server_id] = {
'server': server,
'proxy': proxy,
'rep_url': rep_url,
'pub_url': pub_url,
'out_url': out_url
}
return proxy
except Exception as err:
print 'Error getting server', server_id
print str(err.__class__.__name__), ":", err
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
traceback.print_tb(exc_traceback, limit=30)
return None
开发者ID:akhi28,项目名称:OpenMDAO-Framework,代码行数:32,代码来源:zmqservermanager.py
示例2: show_command_error
def show_command_error(self, e):
'''display a command error'''
if isinstance(e, CommandError):
(etype, evalue, etraceback) = e.exception_info
inner_exception = e.inner_exception
message = e.message
force_traceback = False
else:
(etype, evalue, etraceback) = sys.exc_info()
inner_exception = e
message = "uncaught exception"
force_traceback = True
if isinstance(inner_exception, LdbError):
(ldb_ecode, ldb_emsg) = inner_exception
self.errf.write("ERROR(ldb): {0!s} - {1!s}\n".format(message, ldb_emsg))
elif isinstance(inner_exception, AssertionError):
self.errf.write("ERROR(assert): {0!s}\n".format(message))
force_traceback = True
elif isinstance(inner_exception, RuntimeError):
self.errf.write("ERROR(runtime): {0!s} - {1!s}\n".format(message, evalue))
elif type(inner_exception) is Exception:
self.errf.write("ERROR(exception): {0!s} - {1!s}\n".format(message, evalue))
force_traceback = True
elif inner_exception is None:
self.errf.write("ERROR: {0!s}\n".format((message)))
else:
self.errf.write("ERROR({0!s}): {1!s} - {2!s}\n".format(str(etype), message, evalue))
force_traceback = True
if force_traceback or samba.get_debug_level() >= 3:
traceback.print_tb(etraceback)
开发者ID:runt18,项目名称:samba,代码行数:32,代码来源:__init__.py
示例3: printExceptionDetailsToStdErr
def printExceptionDetailsToStdErr():
"""
No idea if all of this is needed, infact I know it is not. But for now why not.
Taken straight from the python manual on Exceptions.
"""
import sys, traceback
exc_type, exc_value, exc_traceback = sys.exc_info()
print2err("*** print_tb:")
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print2err("*** print_exception:")
traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
print2err("*** print_exc:")
traceback.print_exc()
print2err("*** format_exc, first and last line:")
formatted_lines = traceback.format_exc().splitlines()
print2err(str(formatted_lines[0]))
print2err((formatted_lines[-1]))
print2err("*** format_exception:")
print2err(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
print2err("*** extract_tb:")
print2err(repr(traceback.extract_tb(exc_traceback)))
print2err("*** format_tb:")
print2err(repr(traceback.format_tb(exc_traceback)))
print2err("*** tb_lineno:" + str(exc_traceback.tb_lineno))
开发者ID:peteristhegreat,项目名称:ioHub,代码行数:25,代码来源:__init__.py
示例4: excepthook
def excepthook(exception_type, exception_value, tb):
""" Default exception handler """
import traceback
if debug: traceback.print_tb(tb)
showerror('Fatal Error','%s: %s' % (exception_type.__name__,
exception_value))
sys.exit(1)
开发者ID:drroe,项目名称:ParmEd,代码行数:7,代码来源:scripts.py
示例5: ructf_error
def ructf_error(status=110, message=None, error=None, exception=None, request=None, reply=None, body=None):
if message:
sys.stdout.write(message)
sys.stdout.write("\n")
sys.stderr.write("{}\n".format(status))
if error:
sys.stderr.write(error)
sys.stderr.write("\n")
if request or reply:
sys.stderr.write(make_err_message(message, request, reply))
sys.stderr.write("\n")
if body:
sys.stderr.write("BODY:\n")
sys.stderr.write(body)
sys.stderr.write("\n")
if exception:
sys.stderr.write("Exception: {}\n".format(exception))
traceback.print_tb(exception.__traceback__, file=sys.stderr)
sys.stderr.flush()
sys.exit(status)
开发者ID:HackerDom,项目名称:ructf-2016,代码行数:25,代码来源:checker.py
示例6: main
def main(solver=config.user_config.solver):
logging.basicConfig(level=logging.CRITICAL, format='%(levelname)s: %(message)s')
from minpower import solve
dirNm=splitFilename(__file__)[0]
if dirNm=='': dirNm='.'
excludeL=[]
for fileNm in os.listdir(dirNm):
if fileNm in excludeL: continue
testDir = joindir(dirNm, fileNm)
if not os.path.isdir(testDir): continue
print 'testing: ',fileNm
wipeTestSlate(testDir)
fResults=open(joindir(testDir,'results.txt'),'w+')
fError=open(joindir(testDir,'error.txt'),'w+')
sys.stdout=fResults #switch output to results file
if hasPyscript(testDir):
sys.stdout = sys.__stdout__ #switch back to standard outputting
os.system('python {s}'.format(s=hasPyscript(testDir)[0]))
else:
try:
user_config.scenarios = 2
solve.solve_problem(testDir)
sys.stdout = sys.__stdout__ #switch back to standard outputting
fError.close()
os.remove(joindir(testDir,'error.txt'))
except: #write the error to file
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_tb(exc_traceback, file=fError )
traceback.print_exception(exc_type, exc_value, exc_traceback, file=fError)
sys.stdout = sys.__stdout__ #switch back to standard outputting
print '\t had error' #note that this dir produced error
else:
sys.stdout = sys.__stdout__ #switch back to standard outputting
开发者ID:jimmy0415,项目名称:minpower,代码行数:34,代码来源:run_all_cases.py
示例7: run
def run(self, edit):
try:
configuration = PluginUtils.get_project_configuration(self.view.window(), self.view.file_name())
base_path = configuration.get("base-path")
test_path = configuration.get("test-path")
if not base_path or not test_path:
sublime.message_dialog("This project has not been configured for Jasmine boilerplate generation.\n\nRight click on the base and test folders to configure.")
return
output_files = AngularJasmineBoilerplateCommand.run_command(self, base_path, test_path)
if output_files[0].find(OUTPUT_ALREADY_EXISTS) != -1: # TODO: Update when we support multiple files
if sublime.ok_cancel_dialog("Boilerplate file " + output_files[0], "Overwrite"):
output_files = AngularJasmineBoilerplateCommand.run_command(self, base_path, test_path, True)
else:
return
for file in output_files:
if file:
self.view.window().open_file(test_path + "/" + file)
except:
print("Unexpected error({0}): {1}".format(sys.exc_info()[0], sys.exc_info()[1]))
traceback.print_tb(sys.exc_info()[2])
sublime.message_dialog("Unable to generate Jasmine boilerplate.\n\nEnsure that the AngularJS service or controller is annotated correctly.")
开发者ID:namoscato,项目名称:angular-jasmine-boilerplate-sublime,代码行数:26,代码来源:AngularJasmineBoilerplate.py
示例8: printException
def printException():
print '=' * 50
print 'Exception:', sys.exc_info()[1]
print "getcwd()=%s;curdir=%s" % (os.getcwd(), os.curdir)
print 'Traceback:'
traceback.print_tb(sys.exc_info()[2])
print '=' * 50
开发者ID:OpenPTV,项目名称:openptv-python,代码行数:7,代码来源:general.py
示例9: run
def run(self):
try:
self._cmdline.this_module_name = self.__class__.__module__
if multiprocessing.get_start_method() == 'spawn':
common.set_global_options(self._cmdline)
common.sysinit()
signal.signal(signal.SIGTERM, self._sighandler)
self.id = self._channel(self._dp_name, self.__class__)
common.set_current_process(self.id)
pattern.initialize(self.id)
if hasattr(self._cmdline, 'clock') and \
self._cmdline.clock == 'Lamport':
self._logical_clock = 0
self._log = logging.getLogger(str(self))
self._start_comm_thread()
self._lock = threading.Lock()
self._lock.acquire()
self._wait_for_go()
if not hasattr(self, '_da_run_internal'):
self._log.error("Process does not have entry point!")
sys.exit(1)
result = self._da_run_internal()
self.report_times()
except Exception as e:
sys.stderr.write("Unexpected error at process %s:%r"% (str(self), e))
traceback.print_tb(e.__traceback__)
except KeyboardInterrupt as e:
self._log.debug("Received KeyboardInterrupt, exiting")
pass
开发者ID:cmkane01,项目名称:distalgo,代码行数:34,代码来源:sim.py
示例10: report_all
def report_all(hs, qcx2_res, SV=True, **kwargs):
allres = init_allres(hs, qcx2_res, SV=SV, **kwargs)
#if not 'kwargs' in vars():
#kwargs = dict(rankres=True, stem=False, matrix=False, pdf=False,
#hist=False, oxford=False, ttbttf=False, problems=False,
#gtmatches=False)
try:
dump_all(allres, **kwargs)
except Exception as ex:
import sys
import traceback
print('\n\n-----------------')
print('report_all(hs, qcx2_res, SV=%r, **kwargs=%r' % (SV, kwargs))
print('Caught Error in rr2.dump_all')
print(repr(ex))
exc_type, exc_value, exc_traceback = sys.exc_info()
print("*** print_tb:")
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print("*** print_exception:")
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stdout)
print('Caught Error in rr2.dump_all')
print('-----------------\n')
raise
return allres, ex
return allres
开发者ID:Erotemic,项目名称:hotspotter,代码行数:26,代码来源:report_results2.py
示例11: handle_error
def handle_error(self, wrapper, exception, traceback_):
print >> sys.stderr, "exception %s in wrapper %s" % (exception, wrapper)
self.num_errors += 1
if 0: # verbose?
import traceback
traceback.print_tb(traceback_)
return True
开发者ID:BohaoFeng,项目名称:pybindgen,代码行数:7,代码来源:foomodulegen.py
示例12: excepthook
def excepthook(excType, excValue, tracebackobj):
"""
stolen from ERIC IDE!
Global function to catch unhandled exceptions.
@param excType exception type
@param excValue exception value
@param tracebackobj traceback object
"""
separator = '-' * 80
logFile = "error.log"
notice = \
"""An unhandled exception occurred. Please report the problem\n"""\
"""via email to <%s>.\n"""\
"""A log has been written to "%s".\n\nError information:\n""" % \
("[email protected]", os.getcwd())
versionInfo="OptiSim Version:\t" + getattr(ui.mainwindow, "__version__")
timeString = time.strftime("%Y-%m-%d, %H:%M:%S")
tbinfofile = io.StringIO()
traceback.print_tb(tracebackobj, None, tbinfofile)
tbinfofile.seek(0)
tbinfo = tbinfofile.read()
errmsg = '%s: \n%s' % (str(excType), str(excValue))
sections = [separator, timeString, versionInfo, separator, errmsg, separator, tbinfo]
msg = '\n'.join(sections)
try:
f = open(logFile, "w")
f.write(msg)
f.close()
except IOError:
pass
errorbox = QMessageBox()
errorbox.setText(str(notice)+str(msg))
errorbox.exec_()
开发者ID:MiRichter,项目名称:OptiSim,代码行数:35,代码来源:main.py
示例13: fail_info
def fail_info(self,resultproxy):
try:
self.result(resultproxy)
except:
t,v,tb = sys.exc_info()
traceback.print_tb(tb)
return (t,v)
开发者ID:lukasheinrich,项目名称:packtivity,代码行数:7,代码来源:asyncbackends.py
示例14: main
def main(self, options=["--disablewallet", "--testnet", "--disableexchangerates"]):
parser = argparse.ArgumentParser(
description="OpenBazaar Test Framework",
usage="python3 test_framework.py [options]"
)
parser.add_argument('-b', '--binary', required=True, help="the openbazaar-go binary")
parser.add_argument('-d', '--bitcoind', help="the bitcoind binary")
parser.add_argument('-t', '--tempdir', action='store_true', help="temp directory to store the data folders", default="/tmp/")
args = parser.parse_args(sys.argv[1:])
self.binary = args.binary
self.temp_dir = args.tempdir
self.bitcoind = args.bitcoind
self.options = options
failure = False
try:
self.setup_network()
self.run_test()
except TestFailure as e:
print(repr(e))
failure = True
except Exception as e:
print("Unexpected exception caught during testing: " + repr(e))
traceback.print_tb(sys.exc_info()[2])
failure = True
if not failure:
self.teardown(True)
else:
self.teardown(True)
if failure:
sys.exit(1)
开发者ID:cpacia,项目名称:openbazaar-go,代码行数:33,代码来源:test_framework.py
示例15: do_import
def do_import(self,args):
self.ClearPages()
result=[]
fPath=args
if os.path.isdir(fPath):
os.path.walk(fPath,self.SearchQTI1,result)
else:
head,tail=os.path.split(fPath)
self.SearchQTI1(result,head,[tail])
if len(result)==0:
print "No QTI v1 files found in %s"%fPath
else:
for fName,fPath,doc in result:
print "Processing: %s"%fPath
try:
results=doc.MigrateV2(self.cp)
for doc,metadata,log in results:
if isinstance(doc.root,qti2.QTIAssessmentItem):
print "AssessmentItem: %s"%doc.root.identifier
else:
print "<%s>"%doc.root.xmlname
for line in log:
print "\t%s"%line
except:
type,value,tb=sys.exc_info()
print "Unexpected error: %s (%s)"%(type,value)
traceback.print_tb(tb)
开发者ID:arleyschrock,项目名称:qtimigration,代码行数:27,代码来源:qtish.py
示例16: OnSaveButtonClick
def OnSaveButtonClick(self, event):
if self.btn_apply.Enabled:
if not self.main_frame.YesNoMessageDialog(_(u'Para que as modificações sejam salvas é preciso aplicá-las. Continua?'), 'E-Dictor'):
return
else:
self.OnApplyButtonClick(None)
wildcard = _(u"Todos arquivos (*.*)|*.*")
wildcard = _(u"Arquivos de preferências (*.cfg)|*.cfg;*.CFG|") + wildcard
ext = '.cfg'
dir = os.getcwd()
file_name = '*' + ext
dlg = wx.FileDialog(
self, message=_(u"Salvar preferências em arquivo"), defaultDir=dir,
defaultFile=file_name, wildcard=wildcard, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
)
ret = False
if dlg.ShowModal() == wx.ID_OK:
try:
path = dlg.GetPath()
if not path.lower().endswith(ext):
path += ext
__builtin__.log(u'Log: [op:SavePref] [params:CFG, ' + path + ']\n')
cfg_file = codecs.open(path.encode('utf-8'),'w','utf-8')
__builtin__.cfg.set(u'File Settings',u'Recent files', "")
__builtin__.cfg.write(cfg_file)
ret = True
except:
msg = str(sys.exc_info()[0]) + ':' + str(sys.exc_info()[1]) + '\n' + str(sys.exc_info()[2])
__builtin__.log(str(sys.exc_info()[0]) + ':' + str(sys.exc_info()[1]) + '\n')
traceback.print_tb(sys.exc_info()[2], None, open(__builtin__.log_file.name, "a"))
wx.MessageBox(_(u"Não foi possível salvar o arquivo."),"E-Dictor")
dlg.Destroy()
return ret
开发者ID:edictor,项目名称:edictor,代码行数:34,代码来源:PreferencesDialog.py
示例17: handle_indexing
def handle_indexing(app, mysql):
with app.app_context():
while(True):
try:
g.conn = mysql.connect()
g.cursor = g.conn.cursor()
g.conn.begin()
# run indexing servie every 300 seconds
time.sleep(300)
sqlpie.Indexer().index_documents()
g.conn.commit()
except Exception as e:
if sqlpie.Util.is_debug():
traceback.print_tb(sys.exc_info()[2])
try:
g.conn.rollback()
except:
pass
finally:
# if the MySQL Server is not running, this will fail.
try:
g.cursor.close()
g.conn.close()
except:
pass
开发者ID:lessaworld,项目名称:SQLpie,代码行数:25,代码来源:application.py
示例18: excepthook
def excepthook(exception_type, exception_value, traceback_obj):
"""Global function to catch unhandled exceptions."""
separator = '-' * 80
notice = \
"""An unhandled exception occurred. Please report this error using\n"""\
"""GitHub Issues <https://github.com/gimu/hitagi-reader/issues>."""\
"""\n\nException saved in error.log"""\
"""\n\nError information:\n"""
time_string = time.strftime("%Y-%m-%d, %H:%M:%S")
tbinfofile = io.StringIO()
traceback.print_tb(traceback_obj, None, tbinfofile)
tbinfofile.seek(0)
tbinfo = tbinfofile.read()
# Create error message
error_msg = '%s: \n%s' % (str(exception_type), str(exception_value))
sections = [separator, time_string, separator, error_msg, separator, tbinfo]
# Combine and write to file
msg = '\n'.join(sections)
try:
f = open('error.log', 'w')
f.write(msg)
f.close()
except IOError:
pass
# GUI message
error_box = QMessageBox()
error_box.setWindowTitle('Error occured')
error_box.setText(str(notice) + str(msg))
error_box.exec_()
开发者ID:gimu,项目名称:hitagi-reader.py,代码行数:32,代码来源:Hitagi.py
示例19: showTraceback
def showTraceback( self ):
import traceback
type, value = sys.exc_info()[:2]
print "________________________\n"
print "Exception", type, ":", value
traceback.print_tb( sys.exc_info()[2] )
print "________________________\n"
开发者ID:Kiyoshi-Hayasaka,项目名称:DIRAC,代码行数:7,代码来源:dirac-admin-accounting-cli.py
示例20: parseText
def parseText(self,article_text):
try:
#link = simpleWiki.getMediaWikiFirstLink(article_text)
link = simpleWiki.getNthLink(article_text,2)
writeLink(self.title,link,self.linksFile)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_tb(exc_traceback, limit=1, file=sys.stderr)
'''
article_text = removeBalanced(article_text,'{{','}}')
#article_text = removeBalanced(article_text,'(',')')
# article_text = re.sub(r'\{\{[\s\S]*?\}\}','',article_text)
article_text = re.sub(r'\[\[([Ii]mage|[Ff]ile)[\s\S]*?\]\]\n','',article_text) # remove image links
# article_text = re.sub(r'\([\s\S]*?\)','',article_text) # remove paretheses
article_text = re.sub(r'<\!--[\s\S]*?-->','',article_text) # remove html remarks
article_text = re.sub(r'<!--[\s\S]*?-->','',article_text) # remove html remarks
article_text = re.sub(r'\:\'\'.*?\'\'','',article_text) # remove wiki italics
article_text = re.sub(r'<ref[\s\S]*?</ref>','',article_text) # revmoe refs
article_text = re.sub(r'\(from \[\[[\s\S]*?\)','',article_text)
article_text = re.sub(r'\[\[wikt\:[\s\S]*?\]\]','',article_text) # wikitionary links
if verbose:
print article_text
firstlink = getFirstLink(article_text)
writeLink(self.title,firstlink,self.linksFile)
'''
return True
开发者ID:imclab,项目名称:wikilosophy,代码行数:30,代码来源:zmq_wikiarticle_client.py
注:本文中的traceback.print_tb函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论