Here are the examples of the python api sys.exc_traceback taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
23 Examples
3
Example 1
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
self.server = server
try:
self.setup()
self.handle()
self.finish()
finally:
sys.exc_traceback = None # Help garbage collection
3
Example 2
Project: LibrERP Source File: letter_mgmt.py
def _name_get_intref(self, cr, uid, ids, prop, unknow_none, context=None):
if not len(ids):
return []
reads = self.read(cr, uid, ids, ['id', 'int_ref'], context=context)
res = []
for record in reads:
try:
(model_name, obj_id) = record['int_ref'].split(',')
if model_name and obj_id:
obj_id = int(obj_id)
model = self.pool.get(model_name)
obj_name = model.name_get(cr, uid, [obj_id])[0]
if obj_name and len(obj_name) > 1 :
print (record['id'], obj_name[1])
res.append((record['id'], obj_name[1]))
except:
print repr(traceback.extract_tb(sys.exc_traceback))
return dict(res)
3
Example 3
Project: LibrERP Source File: letter_mgmt.py
def _get_assigned_letters(self, cr, uid, ids, prop, unknow_none, context=None):
if not len(ids):
return {}
model_name = super(hr_employee, self)._name
res = []
try:
for id in ids:
letter_ids = []
ref_ids = self.pool.get('letter.ref').search(cr, uid, [('int_ref', '=', model_name + ',' + str(id))])
if ref_ids:
for ref in self.pool.get('letter.ref').read(cr, uid, ref_ids, context=context):
letter_ids.append(ref['letter_id'][0])
res.append((id, letter_ids))
except:
print repr(traceback.extract_tb(sys.exc_traceback))
print "res", dict(res)
return dict(res)
3
Example 4
def _get_plant_employees(self, cr, uid, ids, prop, unknow_none, context=None):
if not len(ids):
return {}
res = []
try:
for plant in self.browse(cr, uid, ids, context=context):
employee_ids = []
plant_type_id = plant.plant_type_id.id
if not plant_type_id:
continue
ptype = self.pool['project.plant.type'].browse(cr, uid, plant_type_id, context=context)
for department in ptype.department_ids:
#employee_ids += [department.manager_id.id]
employee_ids += map(lambda e: e.id, department.member_ids)
res.append((plant.id, employee_ids))
except:
_logger.error('%s' % (repr(traceback.extract_tb(sys.exc_traceback))))
return dict(res)
3
Example 5
Project: LibrERP Source File: project_place.py
def get_plant_departments(self, cr, uid, ids, context=None):
if not len(ids):
return {}
res = []
try:
for plant in self.browse(cr, uid, ids, context=context):
department_ids = []
plant_type_id = plant.plant_type_id.id
if not plant_type_id:
continue
ptype = self.pool['project.plant.type'].browse(cr, uid, plant_type_id, context=context)
for department in ptype.department_ids:
department_ids.append(department.id)
res.append((plant.id, department_ids))
except:
_logger.error('%s' % (repr(traceback.extract_tb(sys.exc_traceback))))
return dict(res)
3
Example 6
def _get_moved_products_in(self, cr, uid, ids, prop, unknow_none, context=None):
if not len(ids):
return {}
res = []
try:
for plant in self.browse(cr, uid, ids, context):
res.append((plant.id, self.pool['stock.move'].search(cr, uid, [('location_dest_id', '=', plant.stock_location_id and plant.stock_location_id.id or '')])))
except:
_logger.error('%s' % (repr(traceback.extract_tb(sys.exc_traceback))))
return dict(res)
3
Example 7
def _get_moved_products_out(self, cr, uid, ids, prop, unknow_none, context=None):
if not len(ids):
return {}
res = []
try:
for plant in self.read(cr, uid, ids, ['stock_location_id'], context):
if plant['stock_location_id']:
res.append((plant['id'], self.pool.get('stock.move').search(cr, uid, [('location_id', '=', plant['stock_location_id'][0])])))
except:
_logger.error('%s' % (repr(traceback.extract_tb(sys.exc_traceback))))
return dict(res)
3
Example 8
def _get_plant_employees(self, cr, uid, ids, prop, unknow_none, context=None):
if not len(ids):
return {}
res = []
try:
for place in self.browse(cr, uid, ids, context=context):
employee_ids = []
plant_ids = place.plant_ids
for plant in self.pool[project.plant].browse(cr, uid, plant_ids, context=context):
for department in plant.plant_type_id.department_ids:
employee_ids += map(lambda e: e.id, department.member_ids)
res.append((place.id, employee_ids))
except:
_logger.error('%s' % (repr(traceback.extract_tb(sys.exc_traceback))))
return dict(res)
3
Example 9
def _get_moved_products_in(self, cr, uid, ids, prop, unknow_none, context=None):
if not len(ids):
return {}
res = []
try:
for place in self.read(cr, uid, ids, ['stock_location_id']):
if place['stock_location_id']:
res.append((place['id'], self.pool.get('stock.move').search(cr, uid, [('location_dest_id', '=', place['stock_location_id'][0])])))
except:
_logger.error('%s' % (repr(traceback.extract_tb(sys.exc_traceback))))
return dict(res)
3
Example 10
def _get_moved_products_out(self, cr, uid, ids, prop, unknow_none, context=None):
if not len(ids):
return {}
res = []
try:
for place in self.read(cr, uid, ids, ['stock_location_id']):
if place['stock_location_id']:
res.append((place['id'], self.pool.get('stock.move').search(cr, uid, [('location_id', '=', place['stock_location_id'][0])])))
except:
_logger.error('%s' % (repr(traceback.extract_tb(sys.exc_traceback))))
return dict(res)
3
Example 11
def finish_request(self, request, client_address):
try:
rbufsize = -1
wbufsize = 0
rfile = request.makefile('rb', rbufsize)
wfile = request.makefile('wb', wbufsize)
pickle_data = rfile.readline().strip()
migrant = pickle.loads(pickle_data)
with self._lock:
self.migrants.append(migrant)
if not wfile.closed:
wfile.flush()
wfile.close()
rfile.close()
finally:
sys.exc_traceback = None
3
Example 12
Project: PyAutoC Source File: cfmfile.py
def __init__(self, path = None):
self.version = 1
self.fragments = []
self.path = path
if path is not None and os.path.exists(path):
currentresref = Res.CurResFile()
resref = Res.FSpOpenResFile(path, 1)
Res.UseResFile(resref)
try:
try:
data = Res.Get1Resource('cfrg', 0).data
except Res.Error:
raise Res.Error, "no 'cfrg' resource found", sys.exc_traceback
finally:
Res.CloseResFile(resref)
Res.UseResFile(currentresref)
self.parse(data)
if self.version != 1:
raise error, "unknown 'cfrg' resource format"
0
Example 13
Project: pydoctor Source File: driver.py
def main(args):
import cPickle
options, args = parse_args(args)
exitcode = 0
if options.configfile:
readConfigFile(options)
try:
# step 1: make/find the system
if options.systemclass:
systemclass = findClassFromDottedName(options.systemclass,
'--system-class')
if not issubclass(systemclass, model.System):
msg = "%s is not a subclass of model.System"
error(msg, systemclass)
else:
systemclass = zopeinterface.ZopeInterfaceSystem
if options.inputpickle:
system = cPickle.load(open(options.inputpickle, 'rb'))
if options.systemclass:
if type(system) is not systemclass:
cls = type(system)
msg = ("loaded pickle has class %s.%s, differing "
"from explicitly requested %s")
error(msg, cls.__module__, cls.__name__,
options.systemclass)
else:
system = systemclass()
# Once pickle support is removed, always instantiate System with
# options and make fetchIntersphinxInventories private in __init__.
system.options = options
system.fetchIntersphinxInventories()
system.urlprefix = ''
if options.moresystems:
moresystems = []
for fnamepref in options.moresystems:
fname, prefix = fnamepref.split(':', 1)
moresystems.append(cPickle.load(open(fname, 'rb')))
moresystems[-1].urlprefix = prefix
moresystems[-1].options = system.options
moresystems[-1].subsystems.append(system)
system.moresystems = moresystems
system.sourcebase = options.htmlsourcebase
if options.abbrevmapping:
for thing in options.abbrevmapping.split(','):
k, v = thing.split('=')
system.abbrevmapping[k] = v
# step 1.5: check that we're actually going to accomplish something here
args = list(args) + options.modules + options.packages
if options.makehtml == MAKE_HTML_DEFAULT:
if not options.outputpickle and not options.testing \
and not options.makeintersphinx:
options.makehtml = True
else:
options.makehtml = False
# Support source date epoch:
# https://reproducible-builds.org/specs/source-date-epoch/
try:
system.buildtime = datetime.datetime.utcfromtimestamp(
int(os.environ['SOURCE_DATE_EPOCH']))
except ValueError, e:
error(e)
except KeyError:
pass
if options.buildtime:
try:
system.buildtime = datetime.datetime.strptime(
options.buildtime, BUILDTIME_FORMAT)
except ValueError, e:
error(e)
# step 2: add any packages and modules
if args:
prependedpackage = None
if options.prependedpackage:
for m in options.prependedpackage.split('.'):
prependedpackage = system.Package(
system, m, None, prependedpackage)
system.addObject(prependedpackage)
initmodule = system.Module(system, '__init__', None, prependedpackage)
system.addObject(initmodule)
for path in args:
path = os.path.abspath(path)
if path in system.packages:
continue
if os.path.isdir(path):
system.msg('addPackage', 'adding directory ' + path)
system.addPackage(path, prependedpackage)
else:
system.msg('addModuleFromPath', 'adding module ' + path)
system.addModuleFromPath(prependedpackage, path)
system.packages.append(path)
# step 3: move the system to the desired state
if not system.packages:
error("The system does not contain any code, did you "
"forget an --add-package?")
system.process()
if system.options.livecheck:
error("write this")
if system.options.projectname is None:
name = '/'.join([ro.name for ro in system.rootobjects])
system.msg(
'warning',
'WARNING: guessing '+name+' for project name', thresh=-1)
system.projectname = name
else:
system.projectname = system.options.projectname
# step 4: save the system, if desired
if options.outputpickle:
system.msg('', 'saving output pickle to ' + options.outputpickle)
del system.options # don't persist the options
f = open(options.outputpickle, 'wb')
cPickle.dump(system, f, cPickle.HIGHEST_PROTOCOL)
f.close()
system.options = options
# step 5: make html, if desired
if options.makehtml:
options.makeintersphinx = True
if options.htmlwriter:
writerclass = findClassFromDottedName(
options.htmlwriter, '--html-writer')
else:
from pydoctor import templatewriter
writerclass = templatewriter.TemplateWriter
system.msg('html', 'writing html to %s using %s.%s'%(
options.htmloutput, writerclass.__module__,
writerclass.__name__))
writer = writerclass(options.htmloutput)
writer.system = system
writer.prepOutputDirectory()
system.epytextproblems = []
if options.htmlsubjects:
subjects = []
for fn in options.htmlsubjects:
subjects.append(system.allobjects[fn])
elif options.htmlsummarypages:
writer.writeModuleIndex(system)
subjects = []
else:
writer.writeModuleIndex(system)
subjects = system.rootobjects
writer.writeIndividualFiles(subjects, options.htmlfunctionpages)
if system.epytextproblems:
def p(msg):
system.msg(('epytext', 'epytext-summary'), msg, thresh=-1, topthresh=1)
p("these %s objects' docstrings are not proper epytext:"
%(len(system.epytextproblems),))
exitcode = 2
for fn in system.epytextproblems:
p(' '+fn)
if options.outputpickle:
system.msg(
'', 'saving output pickle to ' + options.outputpickle)
# save again, with epytextproblems
del system.options # don't persist the options
f = open(options.outputpickle, 'wb')
cPickle.dump(system, f, cPickle.HIGHEST_PROTOCOL)
f.close()
system.options = options
if options.makeintersphinx:
if not options.makehtml:
subjects = system.rootobjects
# Generate Sphinx inventory.
sphinx_inventory = SphinxInventory(
logger=system.msg,
project_name=system.projectname,
)
if not os.path.exists(options.htmloutput):
os.makedirs(options.htmloutput)
sphinx_inventory.generate(
subjects=subjects,
basepath=options.htmloutput,
)
except:
if options.pdb:
import pdb
pdb.post_mortem(sys.exc_traceback)
raise
return exitcode
0
Example 14
def main_loop(self, cmd):
try:
try:
r = eval (cmd, self.parent.namespace, self.parent.namespace)
self.parent.namespace["_"] = r
if r is not None:
print `r`
except SyntaxError:
exec cmd in self.parent.namespace
except Exception, err:
if not isinstance(err, SystemExit):
try:
tb = sys.exc_traceback
if tb:
tb=tb.tb_next
traceback.print_exception (sys.exc_type, sys.exc_value, tb)
except:
#sys.stderr, self.parent.stderr = self.parent.stderr, sys.stderr
traceback.print_exc()
0
Example 15
Project: bup Source File: ftp-cmd.py
def completer(text, state):
global _last_line
global _last_res
global rl_completion_suppress_append
if rl_completion_suppress_append is not None:
rl_completion_suppress_append.value = 1
try:
line = readline.get_line_buffer()[:readline.get_endidx()]
if _last_line != line:
_last_res = _completer_get_subs(line)
_last_line = line
(dir, name, qtype, lastword, subs) = _last_res
if state < len(subs):
sn = subs[state]
sn1 = sn.try_resolve() # find the type of any symlink target
fullname = os.path.join(dir, sn.name)
if stat.S_ISDIR(sn1.mode):
ret = shquote.what_to_add(qtype, lastword, fullname+'/',
terminate=False)
else:
ret = shquote.what_to_add(qtype, lastword, fullname,
terminate=True) + ' '
return text + ret
except Exception as e:
log('\n')
try:
import traceback
traceback.print_tb(sys.exc_traceback)
except Exception as e2:
log('Error printing traceback: %s\n' % e2)
log('\nError in completion: %s\n' % e)
0
Example 16
def _query(self, path, before=None, after=None):
res = []
url = '%s/lookup/%s' % (self.server, path)
params = {}
if self.limit:
params['limit'] = self.limit
if before and after:
params['time_first_after'] = after
params['time_last_before'] = before
else:
if before:
params['time_first_before'] = before
if after:
params['time_last_after'] = after
if params:
url += '?{0}'.format(urllib.urlencode(params))
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header('X-Api-Key', self.apikey)
proxy_args = {}
if self.http_proxy:
proxy_args['http'] = self.http_proxy
if self.https_proxy:
proxy_args['https'] = self.https_proxy
proxy_handler = urllib2.ProxyHandler(proxy_args)
opener = urllib2.build_opener(proxy_handler)
try:
http = opener.open(req)
while True:
line = http.readline()
if not line:
break
yield json.loads(line)
except (urllib2.HTTPError, urllib2.URLError), e:
raise QueryError, str(e), sys.exc_traceback
0
Example 17
def trace(context=1):
"""Return a list of records for the stack below the current exception."""
return getinnerframes(sys.exc_traceback, context) #@UndefinedVariable
0
Example 18
Project: LibrERP Source File: http.py
def dispatch(self, controller, method):
""" Calls the method asked for by the JSON-RPC2 or JSONP request
:param controller: the instance of the controller which received the request
:param method: the method which received the request
:returns: an utf8 encoded JSON-RPC2 or JSONP reply
"""
args = self.httprequest.args
jsonp = args.get('jsonp')
requestf = None
request = None
request_id = args.get('id')
if jsonp and self.httprequest.method == 'POST':
# jsonp 2 steps step1 POST: save call
self.init(args)
self.session.jsonp_requests[request_id] = self.httprequest.form['r']
headers=[('Content-Type', 'text/plain; charset=utf-8')]
r = werkzeug.wrappers.Response(request_id, headers=headers)
return r
elif jsonp and args.get('r'):
# jsonp method GET
request = args.get('r')
elif jsonp and request_id:
# jsonp 2 steps step2 GET: run and return result
self.init(args)
request = self.session.jsonp_requests.pop(request_id, "")
else:
# regular jsonrpc2
requestf = self.httprequest.stream
response = {"jsonrpc": "2.0" }
error = None
try:
# Read POST content or POST Form Data named "request"
if requestf:
self.jsonrequest = simplejson.load(requestf, object_hook=nonliterals.non_literal_decoder)
else:
self.jsonrequest = simplejson.loads(request, object_hook=nonliterals.non_literal_decoder)
self.init(self.jsonrequest.get("params", {}))
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug("--> %s.%s\n%s", controller.__class__.__name__, method.__name__, pprint.pformat(self.jsonrequest))
response['id'] = self.jsonrequest.get('id')
response["result"] = method(controller, self, **self.params)
except openerplib.AuthenticationError:
error = {
'code': 100,
'message': "OpenERP Session Invalid",
'data': {
'type': 'session_invalid',
'debug': traceback.format_exc()
}
}
except xmlrpclib.Fault, e:
error = {
'code': 200,
'message': "OpenERP Server Error",
'data': {
'type': 'server_exception',
'fault_code': e.faultCode,
'debug': "Client %s\nServer %s" % (
"".join(traceback.format_exception("", None, sys.exc_traceback)), e.faultString)
}
}
except Exception:
logging.getLogger(__name__ + '.JSONRequest.dispatch').exception\
("An error occured while handling a json request")
error = {
'code': 300,
'message': "OpenERP WebClient Error",
'data': {
'type': 'client_exception',
'debug': "Client %s" % traceback.format_exc()
}
}
if error:
response["error"] = error
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug("<--\n%s", pprint.pformat(response))
if jsonp:
mime = 'application/javascript'
body = "%s(%s);" % (jsonp, simplejson.dumps(response, cls=nonliterals.NonLiteralEncoder),)
else:
mime = 'application/json'
body = simplejson.dumps(response, cls=nonliterals.NonLiteralEncoder)
r = werkzeug.wrappers.Response(body, headers=[('Content-Type', mime), ('Content-Length', len(body))])
return r
0
Example 19
def _query(self, path, before=None, after=None):
url = '%s/lookup/%s' % (self.server, path)
params = {}
if self.limit:
params['limit'] = self.limit
if before and after:
params['time_first_after'] = after
params['time_last_before'] = before
else:
if before:
params['time_first_before'] = before
if after:
params['time_last_after'] = after
if params:
url += '?{0}'.format(urllib.urlencode(params))
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header('X-Api-Key', self.apikey)
try:
http = urllib2.urlopen(req)
while True:
line = http.readline()
if not line:
break
yield json.loads(line)
except (urllib2.HTTPError, urllib2.URLError), e:
raise self.not_good, str(e), sys.exc_traceback
0
Example 20
@classmethod
def compile_code(cls, code, filename=None, exec_namespace=None):
"""Compile and possibly execute rex code.
Args:
code (str): The python code to compile.
filename (str): File to associate with the code, will default to
'<string>'.
namespace (dict): Namespace to execute the code in. If None, the
code is not executed.
Returns:
Compiled code object.
"""
filename = filename or "<string>"
error_class = Exception if config.catch_rex_errors else None
# compile
try:
pyc = compile(code, filename, 'exec')
except error_class as e:
# trim trace down to only what's interesting
msg = str(e)
r = re.compile(" line ([1-9][0-9]*)")
match = r.search(str(e))
if match:
try:
lineno = int(match.groups()[0])
loc = code.split('\n')
line = loc[lineno - 1]
msg += "\n %s" % line
except:
pass
raise RexError(msg)
# execute
if exec_namespace is not None:
try:
exec pyc in exec_namespace
except error_class as e:
# trim trace down to only what's interesting
import traceback
frames = traceback.extract_tb(sys.exc_traceback)
frames = [x for x in frames if x[0] == filename]
cls._patch_frames(frames, code, filename)
cls._raise_rex_error(frames, e)
return pyc
0
Example 21
def execute_function(self, func, *nargs, **kwargs):
"""
Execute a function object within the execution context.
@returns The result of the function call.
"""
# makes a copy of the func
import types
fn = types.FunctionType(func.func_code,
func.func_globals.copy(),
name=func.func_name,
argdefs=func.func_defaults,
closure=func.func_closure)
fn.func_globals.update(self.globals)
error_class = Exception if config.catch_rex_errors else None
try:
return fn(*nargs, **kwargs)
except error_class as e:
# trim trace down to only what's interesting
import traceback
frames = traceback.extract_tb(sys.exc_traceback)
filepath = inspect.getfile(func)
if os.path.exists(filepath):
frames = [x for x in frames if x[0] == filepath]
self._raise_rex_error(frames, e)
0
Example 22
def completer(text, state):
global _last_line
global _last_res
global rl_completion_suppress_append
if rl_completion_suppress_append is not None:
rl_completion_suppress_append.value = 1
try:
line = readline.get_line_buffer()[:readline.get_endidx()]
if _last_line != line:
_last_res = _completer_get_subs(line)
_last_line = line
(dir, name, qtype, lastword, subs) = _last_res
if state < len(subs):
sn = subs[state]
sn1 = sn.try_resolve() # find the type of any symlink target
fullname = os.path.join(dir, sn.name)
if stat.S_ISDIR(sn1.mode):
ret = shquote.what_to_add(qtype, lastword, fullname+'/',
terminate=False)
else:
ret = shquote.what_to_add(qtype, lastword, fullname,
terminate=True) + ' '
return text + ret
except Exception, e:
log('\n')
try:
import traceback
traceback.print_tb(sys.exc_traceback)
except Exception, e2:
log('Error printing traceback: %s\n' % e2)
log('\nError in completion: %s\n' % e)
0
Example 23
Project: anvil Source File: __main__.py
def main():
"""Starts the execution of anvil without injecting variables into
the global namespace. Ensures that logging is setup and that sudo access
is available and in-use.
Arguments: N/A
Returns: 1 for success, 0 for failure and 2 for permission change failure.
"""
# Do this first so people can see the help message...
args = opts.parse(load_previous_settings())
# Configure logging levels
log_level = logging.INFO
if args['verbose']:
log_level = logging.DEBUG
logging.setupLogging(log_level, tee_filename=args['tee_file'])
LOG.debug("Log level is: %s" % (logging.getLevelName(log_level)))
def print_exc(exc):
if not exc:
return
msg = str(exc).strip()
if not msg:
return
if not (msg.endswith(".") or msg.endswith("!")):
msg = msg + "."
if msg:
print(msg)
def print_traceback():
traceback = None
if log_level < logging.INFO:
# See: http://docs.python.org/library/traceback.html
# When its not none u get more detailed info about the exception
traceback = sys.exc_traceback
tb.print_exception(sys.exc_type, sys.exc_value,
traceback, file=sys.stdout)
try:
run(args)
utils.goodbye(True)
return 0
except excp.PermException as e:
print_exc(e)
print(("This program should be running via %s as it performs some root-only commands is it not?")
% (colorizer.quote('sudo', quote_color='red')))
return 2
except excp.OptionException as e:
print_exc(e)
print("Perhaps you should try %s" % (colorizer.quote('--help', quote_color='red')))
return 1
except Exception:
utils.goodbye(False)
print_traceback()
return 1