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
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)
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.')
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
def execute(self): self.console.setPlainText('') try: code = self.text.toPlainText() inExampleTable = self.inExampleTable inDistanceMatrix = self.inDistanceMatrix inNetwork = self.inNetwork outExampleTable = None outDistanceMatrix = None outNetwork = None exec(str(code)) self.send("outExampleTable", outExampleTable) self.send("outDistanceMatrix", outDistanceMatrix) self.send("outNetwork", outNetwork) except: message = str(sys.exc_info()[0]) + "\n" message += str(sys.exc_info()[1]) + "\n" message += "LINE=" + str(traceback.tb_lineno( sys.exc_info()[2])) + "\n" self.console.setPlainText(message)
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)
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
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
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: %s" % 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
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 = '******' velo_user = '******' velo_pass = '******' 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)
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
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)
def drop_exception(self): exc_type, exc_obj, tb = sys.exc_info() if exc_obj is None: exc_obj = self.logID lineno = traceback.tb_lineno(traceback) filename = os.path.basename(__file__) linecache.checkcache(filename) line = linecache.getline(filename, lineno, globals()) self.report( "\n" "--------------------------------------------------------------------------------- \n" "Tracking from: {0} \n" "At line number: {1} \n" "Details code: {2} \n" "{3} \n" "--------------------------------------------------------------------------------- \n" .format(os.path.basename(filename), lineno, line.strip(), exc_obj)) return # ------------------------------------------------------------------------------------------------------------- # Created by panda on 2/03/2019 - 3:26 AM # © 2017 - 2018 DAMGteam. All rights reserved
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
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)
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)
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 = "*****@*****.**", to = "*****@*****.**", subject = "Melbourne Journey ERROR", body = logMesg + " " + logMesgDetail) finalResults = [] finalResults.append({'status': "WORQ-ERROR", 'message': message}) handler.response.out.write(simplejson.dumps(finalResults))
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)
def traceError(self, e, exc_tb): while exc_tb: tb = traceback.format_tb(exc_tb) self.notifyLog('%s' % e, level=xbmc.LOGERROR) self.notifyLog('In module: %s' % sys.argv[0].strip() or '<not defined>', level=xbmc.LOGERROR) self.notifyLog('At line: %s' % traceback.tb_lineno(exc_tb), level=xbmc.LOGERROR) self.notifyLog('In file: %s' % tb[0].split(",")[0].strip()[6:-1], level=xbmc.LOGERROR) exc_tb = exc_tb.tb_next
def traceError(self, err, exc_tb): while exc_tb: tb = traceback.format_tb(exc_tb) self.notifyLog('%s' % err, level=xbmc.LOGERROR) self.notifyLog('in module: %s' % (sys.argv[0].strip() or '<not defined>'), level=xbmc.LOGERROR) self.notifyLog('at line: %s' % traceback.tb_lineno(exc_tb), level=xbmc.LOGERROR) self.notifyLog('in file: %s' % tb[0].split(",")[0].strip()[6:-1],level=xbmc.LOGERROR) exc_tb = exc_tb.tb_next
def traceError(err, exc_tb): while exc_tb: tb = traceback.format_tb(exc_tb) notifyLog('%s' % err, xbmc.LOGERROR) notifyLog('in module: %s' % (sys.argv[0].strip() or '<not defined>'), xbmc.LOGERROR) notifyLog('at line: %s' % traceback.tb_lineno(exc_tb), xbmc.LOGERROR) notifyLog('in file: %s' % tb[0].split(",")[0].strip()[6:-1],xbmc.LOGERROR) exc_tb = exc_tb.tb_next
def log_error(self, error_message, extra=None): err_msg = "[STUN_Server] Line #%s: %s\n\n%s" % (str( traceback.tb_lineno( sys.exc_traceback)), traceback.format_exc(), sys.exc_info()) timestamp = time.time() date_string = datetime.datetime.fromtimestamp(timestamp).strftime( '(%Y-%m-%d) %H:%M:%S') self.error_log.append((timestamp, date_string, err_msg, extra))
def print_debug(e): 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)
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 import traceback exception = traceback.format_exception_only(t, value) logger.error('Error executing a python function in %s:\n%s', realfile, ''.join(exception)) # Strip 'us' from the stack (better_exec call) tb = tb.tb_next textarray = text.split('\n') linefailed = traceback.tb_lineno(tb) tbextract = traceback.extract_tb(tb) tbformat = "\n".join(traceback.format_list(tbextract)) logger.error( "The stack trace of python calls that resulted in this exception/failure was:" ) for line in tbformat.split('\n'): logger.error(line) logger.error("The code that was being executed was:") _print_trace(textarray, linefailed) logger.error("(file: '%s', lineno: %s, function: %s)", tbextract[0][0], tbextract[0][1], tbextract[0][2]) # See if this is a function we constructed and has calls back into other functions in # "text". If so, try and improve the context of the error by diving down the trace level = 0 nexttb = tb.tb_next while nexttb is not None: if tbextract[level][0] == tbextract[level + 1][0] and tbextract[ level + 1][2] == tbextract[level][0]: _print_trace(textarray, tbextract[level + 1][1]) logger.error("(file: '%s', lineno: %s, function: %s)", tbextract[level + 1][0], tbextract[level + 1][1], tbextract[level + 1][2]) else: break nexttb = tb.tb_next level = level + 1 raise
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 import traceback exception = traceback.format_exception_only(t, value) logger.error("Error executing a python function in %s:\n%s", realfile, "".join(exception)) # Strip 'us' from the stack (better_exec call) tb = tb.tb_next textarray = text.split("\n") linefailed = traceback.tb_lineno(tb) tbextract = traceback.extract_tb(tb) tbformat = "\n".join(traceback.format_list(tbextract)) logger.error("The stack trace of python calls that resulted in this exception/failure was:") for line in tbformat.split("\n"): logger.error(line) logger.error("The code that was being executed was:") _print_trace(textarray, linefailed) logger.error("(file: '%s', lineno: %s, function: %s)", tbextract[0][0], tbextract[0][1], tbextract[0][2]) # See if this is a function we constructed and has calls back into other functions in # "text". If so, try and improve the context of the error by diving down the trace level = 0 nexttb = tb.tb_next while nexttb is not None: if tbextract[level][0] == tbextract[level + 1][0] and tbextract[level + 1][2] == tbextract[level][0]: _print_trace(textarray, tbextract[level + 1][1]) logger.error( "(file: '%s', lineno: %s, function: %s)", tbextract[level + 1][0], tbextract[level + 1][1], tbextract[level + 1][2], ) else: break nexttb = tb.tb_next level = level + 1 raise
def main(args): from alis import almsgs from alis import alload from alis import alis msgs = almsgs.msgs() # argflag debug = True # There are two instances of this (one is in alis just above) if debug: msgs.bug("Read in resolution from column of data", verbose=2) msgs.bug( "With voigt function, if the user says to put an O I profile in specid A, make sure there is actually an O I line in specid A.", verbose=2) msgs.bug("Prepare a separate .py file for user-created functions", verbose=2) msgs.bug( "Assign a number to every warning and error -- describe this in the manual", verbose=2) msgs.bug( "If emission is not specified for a specid before absorption (in a model with several specid's), the specid printed as an error is always one before", verbose=2) argflag = alload.optarg(os.path.realpath(__file__), argv=args) # Assign filelist: # if sys.argv[-1].split('.')[-1] != 'mod': alload.usage(argflag) # else: argflag['run']['modname'] = sys.argv[-1] alis.ClassMain(argflag) else: try: argflag = alis.alload.optarg(os.path.realpath(__file__), argv=args) # Assign filelist: # if sys.argv[-1].split('.')[-1] != 'mod': alload.usage(argflag) # else: argflag['run']['modname'] = sys.argv[-1] alis.ClassMain(argflag) except Exception: # There is a bug in the code, print the file and line number of the error. et, ev, tb = sys.exc_info() while tb: co = tb.tb_frame.f_code filename = str(co.co_filename) line_no = str(traceback.tb_lineno(tb)) tb = tb.tb_next filename = filename.split('/')[-1] msgs.bug("There appears to be a bug on Line " + line_no + " of " + filename + " with error:" + msgs.newline() + str(ev) + msgs.newline() + "---> please contact the author", verbose=2) except SystemExit: # The code has found an error in the user input and terminated early. pass except: msgs.bug( "There appears to be an undefined (and therefore unhelpful) bug" + msgs.newline() + "---> please contact the author", verbose=2)
def _print_exception_details(): et, ev, tb = sys.exc_info() while tb: co = tb.tb_frame.f_code filename = str(co.co_filename) line_no = str(traceback.tb_lineno(tb)) print "%s:%s" % (filename, line_no) tb = tb.tb_next print "%s: %s" % (et, ev)
def RemoteExec(self, script, *kwargs): try: exec(script, kwargs) except Exception: _e_type, e_value, e_traceback = sys.exc_info() line_no = traceback.tb_lineno(get_last_traceback(e_traceback)) return (-1, "RemoteExec script failed!\n\nLine %d: %s\n\t%s" % (line_no, e_value, script.splitlines()[line_no - 1])) return (0, kwargs.get("returnVal", None))
def to_dict(self): import traceback return { "name": self._name, "detail": self._detail, "critical": self.is_critical(), "lineno": traceback.tb_lineno(self._trbk), }
def main(args): import sys, os from pypit import pypit from pypit.scripts import qa_html import traceback # Import PYPIT routines # Initiate logging for bugs and command line help # These messages will not be saved to a log file # Set the default variables qck = False cpu = 1 #vrb = 2 # Load options from command line debug['develop'] = debug['develop'] or args.develop debug['arc'] = debug['arc'] or args.debug_arc splitnm = os.path.splitext(args.pypit_file) if splitnm[1] != '.pypit': initmsgs.error("Bad extension for PYPIT reduction file."+initmsgs.newline()+".pypit is required") logname = splitnm[0] + ".log" # Execute the reduction, and catch any bugs for printout if debug['develop']: pypit.PYPIT(args.pypit_file, progname=pypit.__file__, quick=qck, ncpus=cpu, verbosity=args.verbosity, use_masters=args.use_masters, devtest=args.devtest, logname=logname, debug=debug) else: try: pypit.PYPIT(args.pypit_file, progname=pypit.__file__, quick=qck, ncpus=cpu, verbosity=args.verbosity, use_masters=args.use_masters, devtest=args.devtest, logname=logname, debug=debug) except: # There is a bug in the code, print the file and line number of the error. et, ev, tb = sys.exc_info() filename, line_no = "<filename>", "<line_no>" while tb: co = tb.tb_frame.f_code filename = str(co.co_filename) try: line_no = str(traceback.tb_lineno(tb)) except AttributeError: # Python 3 line_no = 'UNDEFINED' tb = tb.tb_next filename = filename.split('/')[-1] if str(ev) != "": initmsgs.bug("There appears to be a bug on Line " + line_no + " of " + filename + " with error:" + initmsgs.newline() + str(ev) + initmsgs.newline() + "---> please contact the authors") # Get armsgs instance to terminate from pypit.armsgs import get_logger get_logger().close() return 1 return 0
def print_debug(e): """ Print an exceptions relavent information """ 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]) _, _, tb = sys.exc_info() print '6', traceback.print_tb(tb)
def format_exception(t=None, e=None, tb=None): return dict(exception=dict( type=dict(name=t.__name__, module=t.__module__) if t else None, message=str(e), args=getattr(e, 'args', None), format=traceback.format_exception_only(t, e)) if e else None, traceback=dict(lineno=traceback.tb_lineno(tb) if hasattr( traceback, 'tb_lineno') else tb.tb_lineno, strack=traceback.format_stack(tb.tb_frame), format=traceback.format_tb(tb)) if tb else None, format=traceback.format_exception(t, e, tb))
def errorHandler(self, e): self.GeniusCtrl.log(str(e)+'\n') et, ev, tb = sys.exc_info() while tb : co = tb.tb_frame.f_code filename = str(co.co_filename) line_no = str(traceback.tb_lineno(tb)) self.GeniusCtrl.log(filename+':'+line_no+'\n') tb = tb.tb_next self.GeniusCtrl.log('Error: '+et+':'+ev+'\n') self.running=False
def errorHandler(self, e): self.GeniusCtrl.log(str(e) + '\n') et, ev, tb = sys.exc_info() while tb: co = tb.tb_frame.f_code filename = str(co.co_filename) line_no = str(traceback.tb_lineno(tb)) self.GeniusCtrl.log(filename + ':' + line_no + '\n') tb = tb.tb_next self.GeniusCtrl.log('Error: ' + et + ':' + ev + '\n') self.running = False
def print_debug(): import traceback import sys et, ev, tb = sys.exc_info() while tb: co = tb.tb_frame.f_code print "Filename = " + str(co.co_filename) print "Error Line # = " + str(traceback.tb_lineno(tb)) tb = tb.tb_next print "et = ", et print "ev = ", ev
def format_debug(e): """ Return a string of an exceptions relavent information """ _, _, tb = sys.exc_info() return '1: {doc} \n2: {exec_info} \n3: {exec_0} \n 4: {exec_1} \n5: {lineno} \n6: {stack}'.format( doc=e.__doc__, exec_info=sys.exc_info(), exec_0=sys.exc_info()[0], exec_1=sys.exc_info()[1], lineno=traceback.tb_lineno(sys.exc_info()[2]), stack=traceback.print_tb(tb))
def printException(): exceptiontype, exceptionmessage, tracebackobject = sys.exc_info() while tracebackobject: code = tracebackobject.tb_frame.f_code filenamestring = code.co_filename filenameparts = filenamestring.split("\\") filenametext = filenameparts[len(filenameparts) - 1] print "Exception in: " + filenametext + " (line " + str( traceback.tb_lineno(tracebackobject)) + ")" sayAll("Exception in: " + filenametext + " (line " + str(traceback.tb_lineno(tracebackobject)) + ")") tracebackobject = tracebackobject.tb_next print "Exception type: " + str(exceptiontype) print "Exception message: " + str(exceptionmessage) sayAll("Exception type: " + str(exceptiontype)) sayAll("Exception message: " + str(exceptionmessage))
def _get_project_location(self): """Return the abs path and line number of the line of project code that was being executed when the exception was raised. """ exc_type, exc_value, exc_traceback = sys.exc_info() location_tup = () while exc_traceback: co = exc_traceback.tb_frame.f_code if co.co_filename.startswith(django.conf.settings.BASE_DIR): location_tup = co.co_filename, str( traceback.tb_lineno(exc_traceback)) exc_traceback = exc_traceback.tb_next return location_tup
def open_socket(self): try: self.serverH2RG = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "opening host: "+self.hostH2RG+" port: "+`self.portH2RG` self.serverH2RG.connect((self.hostH2RG,self.portH2RG)) self.serverH2RG.settimeout(30) # .5 min except socket.error, (value,message): exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() if self.serverH2RG: self.serverH2RG.close() print "Could not open socket: " + message print "*** lineno:", traceback.tb_lineno(exceptionTraceback) sys.exit(1)
def get_file(request): if request.method == 'POST': try: filename = json.loads(request.body)['file'] # site_user = request.user # uncomment for production site_user = '******' remote_file_path = '/User Documents/' + site_user + '/' + filename print ' setting up local directory to recieve file' local_path = os.getcwd() + '/userdata/' + site_user path = local_path.split('/') remote_path = remote_file_path.split('/') remote_folder_index = remote_path.index(site_user) prefix = '' for i in range(path.index(site_user)): prefix += path[i] + '/' if not os.path.isdir(prefix): print ' creating new folder1 ', prefix os.makedirs(prefix) for i in range(remote_folder_index, len(remote_path) - 1): print ' checking if dir exists ', prefix + remote_path[i] if not os.path.isdir(prefix + remote_path[i]): prefix += remote_path[i] + '/' print ' creating new folder2 ', prefix os.makedirs(prefix) print 'fatching ', filename, ' from ', remote_file_path, ' and copying it to local directory ', prefix process = Popen( ['python', './apps/velo/get_file.py', remote_file_path, prefix, filename, site_user, 'acmetest', 'acmetest'], stdout=PIPE) (out, err) = process.communicate() exit_code = process.wait() out = out.splitlines(True)[1:] print 'sending text file to server \n', out return HttpResponse(out, content_type='text/plain') 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)
def _show_error(): """ show system errors """ et, ev, tb = sys.exc_info() print "Error Type: %s" % et print "Error Value: %s" % ev while tb : co = tb.tb_frame.f_code filename = str(co.co_filename) line_no = str(traceback.tb_lineno(tb)) print ' %s:%s' % (filename, line_no) tb = tb.tb_next
def _show_error(): """ show system errors """ et, ev, tb = sys.exc_info() print "Error Type: %s" % et print "Error Value: %s" % ev while tb: co = tb.tb_frame.f_code filename = str(co.co_filename) line_no = str(traceback.tb_lineno(tb)) print ' %s:%s' % (filename, line_no) tb = tb.tb_next
def check_credentials(request): if request.method == 'POST': try: data = json.loads(request.body) response = {} for s in data: if s == 'esgf': import pyesgf from pyesgf.logon import LogonManager lm = LogonManager() lm.logon_with_openid(data[s]['username'], data[s]['password']) if lm.is_logged_on() != True: response[s] = 'failed' else: response[s] = 'success' if s == 'velo': lib_path = os.path.abspath(os.path.join('apps', 'velo')) sys.path.append(lib_path) import VeloAPI velo_api = VeloAPI.Velo() velo_api.start_jvm() ''' Using the test credentials for the time being, simply uncomment to use the users credentials velo_api.init_velo(data[s]['username'], data[s]['password']) ''' # res = velo_api.init_velo("acmetest", "acmetest") response[s] = 'success' ''' if res.logged_on() != True: resonse[s] = 'failed' else: response[s] = 'success ''' 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) else: return HttpResponse(status=404)
def _traceback_to_trace_info(self): exc_type, exc_value, exc_traceback = sys.exc_info() trace_info_list = [] while exc_traceback: co = exc_traceback.tb_frame.f_code trace_info_list.append(u'{}({})'.format( os.path.basename(co.co_filename), traceback.tb_lineno(exc_traceback), )) exc_traceback = exc_traceback.tb_next if not isinstance(exc_value, d1_common.types.exceptions.DataONEException): trace_info_list.append(u'Type: {}'.format(exc_type)) trace_info_list.append(u'Value: {}'.format(exc_value)) return trace_info_list
def main(): """ """ from data.config import Config def check_all(*paths): for f in paths: MultiCycleCreator.checkCheckFiles(f) return paths #end check_all try: parser = argparse.ArgumentParser() parser.add_argument('-o', '--output-file', default='multicycle.h5', help='path to MPACT output file') parser.add_argument( 'file_path', default=[], help= 'path to cycle base filename with .h5 and .shift.h5 extension (at least two cycles required)', nargs='+', type=MultiCycleCreator.checkCycleFiles #type = check_all ) args = parser.parse_args() if len(args.file_path) < 2: parser.print_usage() else: MultiCycleCreator()(args.output_file, *args.file_path) print '[multicycle_creator] finished' except Exception, ex: msg = str(ex) print >> sys.stderr, msg et, ev, tb = sys.exc_info() while tb: print >> sys.stderr print >> sys.stderr, \ 'File=' + str( tb.tb_frame.f_code ) + \ ', Line=' + str( traceback.tb_lineno( tb ) ) tb = tb.tb_next #end while logging.error(msg)
def send(): # TODO: deal with bad request scenarios requests.post( Debugged.base_url % "report" , auth=(str(Debugged.api_key),""), headers={"Content-Type":"application/json"}, data=json.dumps({ "created_at": now, "identifier": hash, "exception_name": str(etype.__name__), "sdk_version": "python", "stack_trace": ''.join(traceback.format_exception(etype,value, tback)), "line_number": traceback.tb_lineno(tback), "character_number": -1, "filename": exc_info[Debugged.EXC_INFO_FILENAME], "user_custom_data": finished_local_data, "sdk_data": { } }) )
def run(self): try: if self.comp == "server": while True: data = self.soc.recv(buffer) #print "server data: ",data if not data: continue else: if self.fun: try: if zlibBool == True: dict = cPickle.loads(zlib.decompress(data)) if zlibBool == False: dict = cPickle.loads(data) print "GET: ", dict except EOFError: break else: self.fun(dict) if data == "done": break if self.comp == "client": while True: data = self.soc.TCPSock.recv(buffer) #print "client data: ", data if not data: continue else: if self.fun: try: if zlibBool == True: dict = cPickle.loads(zlib.decompress(data)) if zlibBool == False: dict = cPickle.loads(data) print "GET: ", dict except EOFError: break else: self.fun(dict) if data == "done": break except: print "error in getData thread..." print sys.exc_info()[0] print sys.exc_info()[1] print "LINE=",traceback.tb_lineno(sys.exc_info()[2])
def main(): """ """ from data.config import Config def extant_file(f): if not os.path.exists(f): raise argparse.ArgumentTypeError('{0} not found'.format(f)) return f #end extant_file try: parser = argparse.ArgumentParser() parser.add_argument('-m', '--mpact-file', help='path to input MPACT HDF5 file', required=True, type=extant_file) parser.add_argument('-o', '--output-file', default='out.h5', help='path to output HDF5 file') parser.add_argument('-s', '--shift-file', help='path to input Shift HDF5 file', required=True, type=extant_file) args = parser.parse_args() #obj = FluenceSynthesizer() FluenceSynthesizer()(args.mpact_file, args.shift_file, args.output_file) except Exception, ex: msg = str(ex) print >> sys.stderr, msg et, ev, tb = sys.exc_info() while tb: print >> sys.stderr, \ 'File=' + str( tb.tb_frame.f_code ) + \ ', Line=' + str( traceback.tb_lineno( tb ) ) tb = tb.tb_next #end while logging.error(msg)
def download_file(self, filepath, location): # download file from velo try: destFolder = jpype.java.io.File(location) cmsfilepath = cms(filepath) filesToDownload.add(cmsfilepath) resMgr.bulkDownload(filesToDownload, destFolder) return True 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 False
def main(): """ """ from data.config import Config def extant_file(f): if not os.path.exists(f): raise argparse.ArgumentTypeError('{0} not found'.format(f)) return f #end extant_file try: parser = argparse.ArgumentParser() parser.add_argument('-k', '--thickness-file', help='thickness file', required=True, type=extant_file) parser.add_argument('-t', '--temp-file', help='temperature file', required=True, type=extant_file) parser.add_argument('-o', '--output-file', default='out.h5', help='path to output HDF5 file') args = parser.parse_args() obj = CrudSynthesizer() obj(args.temp_file, args.thickness_file, args.output_file) except Exception, ex: msg = str(ex) print >> sys.stderr, msg et, ev, tb = sys.exc_info() while tb: print >> sys.stderr, \ 'File=' + str( tb.tb_frame.f_code ) + \ ', Line=' + str( traceback.tb_lineno( tb ) ) tb = tb.tb_next #end while logging.error(msg)
def handle(self, *args, **options) : ''' Харилцагчийн бүртгэл дээрх диамонд кодуудыг шинэчлэх Excel хүснэгтээс харгалзах диамонд кодуудыг нэг бүрчлэх шинэчлэнэ. print colored : HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' ''' def print_green(msg): print u'\033[92m%s\033[0m' % msg def print_blue(msg): print u'\033[94m%s\033[0m' % msg cursor = connection.cursor() if not args : raise CommandError('Excel file path required.') path = args[0] if path[0] != '/' : path = os.path.join(os.path.dirname(__file__), '../../../' + path) if not os.path.isfile(path) : raise CommandError('Input file does not exists on : ', path) filename = os.path.basename(path) if not '.xls' in filename : raise CommandError('Input file must be only *.xls format : ', filename) try : work_book = xlrd.open_workbook(path) sheet = work_book.sheet_by_index(0) except Exception, e: import traceback et, ev, tb = sys.exc_info() while tb : co = tb.tb_frame.f_code fname = "Filename : " + str(co.co_filename) line_no = "Error Line : " + str(traceback.tb_lineno(tb)) tb = tb.tb_next raise CommandError(e.message + '\n'+fname+'\n'+line_no+'\n '+'Sent it to USI!!!')
def log_error(self): error_message = "Error on: " + \ datetime.today().strftime("%A %d %b %Y %H:%M") + "\n" et, ev, tb = sys.exc_info() while tb: co = tb.tb_frame.f_code error_message += "Filename: " + str(co.co_filename) + "\n" error_message += "Error Line # : " \ + str(traceback.tb_lineno(tb)) + "\n" tb = tb.tb_next error_message += "Type: " + str(et) + "\n" + "Error: " + \ str(ev) + "\n\n" f = open(self.error_file, "a") f.write(error_message) f.close()
def print_tb_last(): tb = sys.exc_info()[2] file = sys.stderr while True: f = tb.tb_frame lineno = traceback.tb_lineno(tb) tb = tb.tb_next if tb is not None: continue co = f.f_code filename = co.co_filename name = co.co_name file.write(' File "%s", line %d, in %s\n' % (filename, lineno, name)) line = linecache.getline(filename, lineno) if line: file.write(' %s\n' % line.strip()) break
def main(): try: if len(sys.argv) < 2: print >> sys.stderr, 'Usage: datamodel.py casl-output-fname' else: data = DataModel(sys.argv[1]) print str(data) #end if-else except Exception, ex: print >> sys.stderr, str(ex) et, ev, tb = sys.exc_info() while tb: print >> sys.stderr, \ 'File=' + str( tb.tb_frame.f_code ) + \ ', Line=' + str( traceback.tb_lineno( tb ) ) tb = tb.tb_next
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
def run(self): self._dbConn = sqlite3.connect(self._dbName) self._dbConn.row_factory = self.dict_factory self._cursor = self._dbConn.cursor() while self.alive.isSet() or not self.input.empty(): try: rid, cmd = self.input.get() self._cursor.execute(cmd) output = [] for row in self._cursor.fetchall(): output.append(row) if cmd[:6] != 'SELECT': self._dbConn.commit() self.output.put((rid, output)) except Exception, e: exc_type, exc_value, exc_traceback = sys.exc_info() dbLogger.error("DatabaseProcessor: %s at line %i", e, traceback.tb_lineno(exc_traceback))
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)
def call(prgname="", getfuncs=False, getinst=False, atomic=None, verbose=2): sendatomic = ['voigt', 'lineemission'] # Add your new function to the following: fd = dict({ 'Afwhm': alfunc_afwhm.AFWHM, 'Ashift': alshift.Ashift, 'brokenpowerlaw': alfunc_brokenpowerlaw.BrokenPowerLaw, 'chebyshev': alfunc_chebyshev.Chebyshev, 'constant': alfunc_constant.Constant, 'gaussian': alfunc_gaussian.Gaussian, 'legendre': alfunc_legendre.Legendre, 'linear': alfunc_linear.Linear, 'lineemission': alfunc_lineemission.LineEmission, 'polynomial': alfunc_polynomial.Polynomial, 'powerlaw': alfunc_powerlaw.PowerLaw, 'random': alfunc_random.Random, 'spline': alfunc_spline.Spline, 'thar': alfunc_thar.ThAr, 'tophat': alfunc_tophat.TopHat, 'variable': alfunc_variable.Variable, 'vfwhm': alfunc_vfwhm.vFWHM, 'voigt': alfunc_voigt.Voigt, 'vshift': alshift.vshift, 'vsigma': alfunc_vsigma.vSigma }) # Load the user-specified functions msgs.info("Loading user functions") try: usr_fd, usr_atm = alfunc_user.load_user_functions() except Exception: msgs.warn("There appears to be a problem loading the user functions") et, ev, tb = sys.exc_info() while tb: co = tb.tb_frame.f_code filename = str(co.co_filename) line_no = str(traceback.tb_lineno(tb)) tb = tb.tb_next filename = filename.split('/')[-1] msgs.bug("A bug has been spotted on Line " + line_no + " of " + filename + " with error:" + msgs.newline() + str(ev)) sys.exit() # Incorporate the user-defined functions kvals = usr_fd.keys() if len(kvals) == 0: msgs.info("No user functions to load!") fdk = fd.keys() # Check there is no overlap in function names for i in range(len(kvals)): if kvals[i] in fdk: msgs.error("There is already a built-in function called '{0:s}'". format(kvals[i]) + msgs.newline() + "Please give your function a new name.") else: fd[kvals[i]] = usr_fd[kvals[i]] msgs.info("Successfully loaded user function: {0:s}".format( kvals[i])) for i in range(len(usr_atm)): if usr_atm[i] in kvals: sendatomic.append(usr_atm[i]) else: msgs.error( "with user-defined function {0:s}".format(usr_atm[i]) + msgs.newline() + "Atomic data request for a function that does not exist!") # Don't touch anything below if getfuncs and getinst: msgs.bug( "Two keywords in alfunc_base.py unexpectedly set to 'True' ...", verbose=2) sys.exit() if getinst: keys = fd.keys() for i in range(len(keys)): if keys[i] in sendatomic: fd[keys[i]] = fd[keys[i]](prgname=prgname, getinst=getinst, verbose=verbose, atomic=atomic) else: fd[keys[i]] = fd[keys[i]](prgname=prgname, getinst=getinst, verbose=verbose) if getfuncs: return fd.keys() else: return fd