• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python traceback.extract_stack函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中traceback.extract_stack函数的典型用法代码示例。如果您正苦于以下问题:Python extract_stack函数的具体用法?Python extract_stack怎么用?Python extract_stack使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了extract_stack函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: parsemessage

    def parsemessage(self, linesiter, properties = {}):
        if DEBUG: log.out("parsemessage(%d) starting" % len(traceback.extract_stack()))
        lastkey = None
        for line in linesiter:
            # if possible (empty lines marks end of header), proceed with content parsing
            if not line:
                if DEBUG: log.out("parsemessage(%d): empty line, %d properties, parsing content" % (len(traceback.extract_stack()), len(properties)))
                content = self.parsecontent(linesiter, properties)
                if not content:
                    if DEBUG: log.out("parsemessage(%d): no content" % len(traceback.extract_stack()))
                    break
                if DEBUG: log.out("parsemessage(%d) leaving with content" % len(traceback.extract_stack()))
                return content

            if line[0] == "\t" or line[0] == " ":
                if not lastkey:
                    continue
                properties[lastkey] += " " + line[1:]
            else:
                p = line.split(": ", 1)
                if len(p) < 2:
                    continue
                lastkey = p[0].lower()
                value = p[1]
                properties[lastkey] = value
        if DEBUG: log.out("parsemessage(%d) leaving without content" % len(traceback.extract_stack()))
开发者ID:martinexner,项目名称:verbot,代码行数:26,代码来源:botmailforward.py


示例2: __init__

 def __init__(self, def_name=None):
     if def_name == None:
         (filename,line_number,function_name,text) = \
             traceback.extract_stack()[-2]
         print traceback.extract_stack()
         def_name = text[:text.find('=')].strip()
     self.instance_name = def_name
开发者ID:RobLeggett,项目名称:codes,代码行数:7,代码来源:get_instance_name.py


示例3: __call__

        def __call__(self, setid, msg, *args, **kwargs):

            if setid not in self.registered:
                raise ValueError, "Not registered debug ID %s" % setid

            if not setid in self.active:
                # don't even compute the metrics, since they might
                # be statefull as RelativeTime
                return

            msg_ = ' / '.join([str(x()) for x in self.__metrics])

            if len(msg_) > 0:
                msg_ = "{%s}" % msg_

            if len(msg) > 0:
                # determine blank offset using backstacktrace
                if self._offsetbydepth:
                    level = len(traceback.extract_stack()) - 2
                else:
                    level = 1

                if len(msg) > 250 and 'DBG' in self.active and not setid.endswith('_TB'):
                    tb = traceback.extract_stack(limit=2)
                    msg += "  !!!2LONG!!!. From %s" % str(tb[0])

                msg = "DBG%s:%s%s" % (msg_, " "*level, msg)
                SetLogger.__call__(self, setid, msg, *args, **kwargs)
            else:
                msg = msg_
                Logger.__call__(self, msg, *args, **kwargs)
开发者ID:kirty,项目名称:PyMVPA,代码行数:31,代码来源:verbosity.py


示例4: log_callstack

def log_callstack(back_trace=False):
    """
    Helper function that formats either a (filtered) backtrace or call stack in a string. Blender internals
    are filtered such that errors in the own code can be detected more easily.

    :param back_trace: If true, the backtrace is returned. Otherwise, the call stack is returned.
    :return: the formatted call stack/backtrace in a string.
    """

    if not back_trace:
        message = BACKTRACE_MESSAGE_CALLSTACK % len([i for i in traceback.extract_stack() if i[2] == 'run'])
        stack = traceback.extract_stack()[:-1]
    else:
        message = BACKTRACE_MESSAGE
        stack = traceback.extract_tb(sys.exc_info()[2])

    last_call = ""
    for path, line, func, code in stack:
        if 'addons' in path:
            file = '...' + path[path.find('addons') + 6:]
        elif 'scripts' in path:
            file = '...' + path[path.find('scripts') + 7:]
        else:
            file = path
        if func not in BACKTRACE_FILTER_FUNC:
            if func in BACKTRACE_FILTER_HIDE_CODE:
                message += BACKTRACE_MESSAGE_STACK.format(func, file, line)
            else:
                message += BACKTRACE_MESSAGE_STACK_CODE.format(func, file, line, code, last_call)
        last_call = code

    return message
开发者ID:HBPNeurorobotics,项目名称:BlenderRobotDesigner,代码行数:32,代码来源:logfile.py


示例5: makeDict

def makeDict(*args):
    strAllStack = str(extract_stack())
    intNumLevels = len( extract_stack() )
    intLevel = 0
    blnFinished = False
    while not blnFinished:
        strStack = str( extract_stack()[intLevel] )
        if strStack.find( "makeDict( ")>0:
            blnFinished = True
        intLevel += 1
        if intLevel >= intNumLevels:
            blnFinished = True
    strStartText = "= makeDict( "
    intLen = len( strStartText )
    intOpenParenLoc = strStack.find( strStartText )
    intCloseParenLoc = strStack.find(")", intOpenParenLoc )
    strArgs = strStack[ intOpenParenLoc+intLen : intCloseParenLoc ].strip()
    lstVarNames = strArgs.split(",")
    lstVarNames = [ s.strip() for s in lstVarNames ]   
    if len( lstVarNames ) == len( args ):
        tplArgs = map( None, lstVarNames, args )
        newDict = dict( tplArgs )
        return newDict
    else:
        print "Error.  makeDict Failed."
        return None
开发者ID:bhramoss,项目名称:code,代码行数:26,代码来源:recipe-576373.py


示例6: main

def main():
    print'begin'                  #如果这里不捕捉异常的话,程序运行到打印出begin就结束了,final是不会被打印的
    try:
        sys.exit('exitok')
    except :
        print traceback.extract_stack()
    print'final'
开发者ID:maxomnis,项目名称:python_example,代码行数:7,代码来源:testexit.py


示例7: test_kmeans

def test_kmeans(filename):
    stripped_name = filename.split("/")[-1].split(".")[0]
    from sklearn.cluster import KMeans
    contents = stripped_name.split("_")
    no_clusters = int(contents[4].split(".")[0])
    confusion_matrices = []
    start_time = time.time()

    df = pd.read_csv(filename)
    h_indep = [d for d in df.columns if "features" in d]
    h_dep = [d for d in df.columns if "class" in d]
    for _ in xrange(10):
        try:
            print "- ",
            sys.stdout.flush()

            indep = df[h_indep]
            dep = df[h_dep]

            kmeans = KMeans(n_clusters =no_clusters)
            kmeans.fit(indep)
            print kmeans.inertia_
            import pdb
            pdb.set_trace()
        except:
            import traceback
            traceback.extract_stack()


    import pickle
    pickle.dump(confusion_matrices, open("./Results_K_Means/Kmeans_" + extract_name, "wb"))
    print " Total Time: ", time.time() - start_time
开发者ID:ai-se,项目名称:HPCCTuning,代码行数:32,代码来源:testing_rig.py


示例8: trace

    def trace(self, entry , params=None):
        """Internal method - see log.trace.__doc__ for details."""
        # Turn the list of values into a printable string.
        if params: 
            paramString = string.join( ['%s' % (param) for param in params] , ', ')
        else:
            paramString = ''

        # Examine the trace stack to get the calling function.
        funcName = traceback.extract_stack()[-3:-2][0][2]
        modName  = traceback.extract_stack()[-3:-2][0][0]

        # Format the message based on entry/exit state.
        if entry.upper() == 'EXIT':
            entry = 'EXIT'
            msg = 'Leaving %s::%s()' % (modName, funcName)
            if paramString:
                 msg += ' with return values: %s' % paramString                
        else:
            entry = 'ENTRY'
            msg = 'Entering %s::%s(%s)' % (modName,
                                           funcName, 
                                           paramString)
        
        # Time to log the message.
        self.__log(entry, msg)
开发者ID:muromec,项目名称:qtopia-ezx,代码行数:26,代码来源:log.py


示例9: lock

    def lock(self):
        """Create an external file lock for the bundle database."""

        from lockfile import FileLock, AlreadyLocked  # , LockTimeout
        import time
        import traceback
        from ..dbexceptions import LockedFailed

        if self._lock:
            tb = traceback.extract_stack()[-5:-4][0]
            global_logger.debug(
                "Already has bundle lock from {}:{}".format(
                    tb[0],
                    tb[1]))
            return

        self._lock = FileLock(self.lock_path)

        for i in range(10):
            try:
                tb = traceback.extract_stack()[-5:-4][0]
                self._lock.acquire(-1)
                global_logger.debug(
                    "Acquired bundle lock from {}:{}".format(
                        tb[0],
                        tb[1]))
                return
            except AlreadyLocked:
                global_logger.debug("Waiting for bundle lock")
                time.sleep(1)

        raise LockedFailed("Failed to acquire lock on {}".format(self.lock_path))
开发者ID:CivicVision,项目名称:ambry,代码行数:32,代码来源:sqlite.py


示例10: sql_query

def sql_query(query_counter,engine,metric_list,query_frequency_dictionary,query_dictionary,sleep_config,log_identifier,redshift_connection,queue_push):
	# Get a list of only those queries that are divisible by the time period set by user
	query_list = [query for (query, period) in query_frequency_dictionary.items() if query_counter%query_frequency_dictionary[query] == 0]
	print query_list
	# Query redshift for each of the chosen queries
	for i in range(0,len(query_list)):
		try:
			print query_list[i]
			query_result_df[query_list[i]] = pd.read_sql_query(query_dictionary[query_list[i]],engine)
		except:
			print 'Something broke. connection failure'
			logging.exception('%s : Redshift connection failure', log_identifier)
			traceback.extract_stack()
			#print type(exception).__name__
			print query_counter
			time.sleep(sleep_config)
			engine = create_rs_engine(log_identifier=log_identifier,redshift_connection=redshift_connection)
			continue
	# Increment the count by 1
	query_counter += 1
	# Put the dataframes on a queue consumed by all threads.
	for i in range(0,queue_push):
		query_result_queue.put(query_result_df)

	return query_counter
开发者ID:myntra,项目名称:RedEye,代码行数:25,代码来源:redshift_monitoring.py


示例11: add_post

def add_post():
	db = get_db()
	fichero = request.files['archivo']
	lineaFichero=1
	for linea in fichero.readlines():
		try:
			partir = linea.split('#')
			titulo = partir[1]
			autor = partir[2]
			texto = partir[3]
			titulo = titulo.decode('utf-8')
			autor = autor.decode('utf-8')
			texto = texto.decode('utf-8')
			unicode(titulo)
			unicode(autor)
			unicode(texto)

			db.execute('INSERT INTO post (title,author,textillo) VALUES (?,?,?)',[unicode(titulo),unicode(autor),unicode(texto)])
			db.commit()
			lineaFichero+=1
		except IndexError as e:
			import traceback, os.path
			top = traceback.extract_stack()[-1]
			flash(str(e)+' - '.join([type(e).__name__, os.path.basename(top[0]), str(top[1])]))
		except UnicodeDecodeError as e:
			import traceback, os.path
			top = traceback.extract_stack()[-1]
			flash(str(e)+' - '.join([type(e).__name__, os.path.basename(top[0]), str(top[1])]))
	flash('Entradas agregadas con exito')
	return redirect(url_for('mostrar_post'))
开发者ID:ekiscrim,项目名称:appblogtxt,代码行数:30,代码来源:routes.py


示例12: test_traceback_stack

    def test_traceback_stack(self):
        import sys
        import traceback

        def C():
            raise Exception

        def B():
            C()

        def A():
            try:
                B()
            except:
                return sys.exc_info()[2]

        lineno = C.func_code.co_firstlineno
        tb = A()

        a = traceback.extract_tb(tb)
        b = traceback.extract_stack(tb.tb_frame, 1)
        self.assertEqual(a, [(__file__, 8+lineno, 'A', 'B()'), (__file__, 4+lineno, 'B', 'C()'), (__file__, 1+lineno, 'C', 'raise Exception')])
        self.assertEqual([x[2] for x in b], ['A']) # only check that we're in the proper function, the rest does not work properly

        tb = tb.tb_next
        a = traceback.extract_tb(tb)
        b = traceback.extract_stack(tb.tb_frame, 2)
        self.assertEqual(a, [(__file__, 4+lineno, 'B', 'C()'), (__file__, 1+lineno, 'C', 'raise Exception')])
        self.assertEqual([x[2] for x in b], ['A', 'B']) # only check that we're in the proper function, the rest does not work properly

        tb = tb.tb_next
        a = traceback.extract_tb(tb)
        b = traceback.extract_stack(tb.tb_frame, 3)
        self.assertEqual(a, [(__file__, 1+lineno, 'C', 'raise Exception')])
        self.assertEqual([x[2] for x in b], ['A', 'B', 'C']) # only check that we're in the proper function, the rest does not work properly
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:35,代码来源:test_regressions.py


示例13: LockCheck

def LockCheck():
    global semaphores
    while 1:
        each = None
        Sleep(5 * 60)
        now = time.time()
        try:
            for each in semaphores.keys():
                BeNice()
                if (each.count<=0) and (each.waiting.balance < 0) and (each.lockedWhen and (now - each.lockedWhen)>=(5*MIN)):
                    logger.error("Semaphore %s appears to have threads in a locking conflict."%id(each))
                    logger.error("holding thread:")
                    try:
                        for s in traceback.format_list(traceback.extract_stack(each.thread.frame,40)):
                            logger.error(s)
                    except:
                        sys.exc_clear()
                    first = each.waiting.queue
                    t = first
                    while t:
                        logger.error("waiting thread %s:"%id(t),4)
                        try:
                            for s in traceback.format_list(traceback.extract_stack(t.frame,40)):
                                logger.error(s,4)
                        except:
                            sys.exc_clear()
                        t = t.next
                        if t is first:
                            break
                    logger.error("End of locking conflict log")
        except StandardError:
            StackTrace()
            sys.exc_clear()
开发者ID:breezechen,项目名称:stacklessexamples,代码行数:33,代码来源:uthread.py


示例14: log

def log(lvl, msg):
   '''
   Formats and prints message to appropriate i/o stream.
   TODO: perhaps look into replace with logging module
   '''

   (
      procName,
      lineNum,
      funcName,
      funcName2
   )= extract_stack()[len(extract_stack())-2]

   msg= "%s, %s, %s, %s, %s, %s\n" % (
      datetime.now(),
      lvl,
      procName,
      funcName,
      lineNum,
      msg
   )

   ioStream= dict(error= stderr).get(lvl, stdout)
   print >> ioStream, msg,
   ioStream.flush()
开发者ID:richardjmarini,项目名称:Impetus-old,代码行数:25,代码来源:logger.py


示例15: PRINT_EXCEPTION

def PRINT_EXCEPTION(e=None, stop=False):
	if not log_level:
		pass
	traceback.extract_stack()[-1][1]
	traceback.print_exc()
	if stop:
		pdb.set_trace()
开发者ID:wydevices,项目名称:wydevices,代码行数:7,代码来源:debug.py


示例16: format_stack_report

def format_stack_report(details, exc_info):
    header = ''
    header += "Exception\n---------\n"
    if exc_info:
        header += ''.join(traceback.format_exception(*exc_info))
        header += "\n"
        # Print out a stack trace too.  The exception stack only contains
        # calls between the try and the exception.
        try:
            stack = util.get_nice_stack()
        except StandardError:
            stack = traceback.extract_stack()
        header += "Call Stack\n---------\n"
        header += ''.join(traceback.format_list(stack))
        header += "\n"
    else:
        # fake an exception with our call stack
        try:
            stack = util.get_nice_stack()
        except StandardError:
            stack = traceback.extract_stack()
        header += ''.join(traceback.format_list(stack))
        header += 'UnknownError: %s\n' % details
        header += "\n"
    return header
开发者ID:CodeforEvolution,项目名称:miro,代码行数:25,代码来源:crashreport.py


示例17: adminInfo

def adminInfo(handler):
	handler.title('Information')
	requirePriv(handler, 'Admin')

	print "<div class=\"info\">"

	print "<h3>Uptime</h3>"
	loadTime = getLoadtime()
	print "Started %s<br>" % loadTime
	print "Up for %s<br>" % timesince(loadTime)
	print "Total requests: %d<br>" % server().getTotalRequests()
	print "<form method=\"post\" action=\"/admin/restart\">"
	print Button('Restart', type = 'submit').negative()
	print "</form>"

	print "<h3>Threads</h3>"
	print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"
	print "<tr><th>ID</th><th class=\"main\">Name</th><th>Alive</th><th>Daemon</th></tr>"
	for thread in sorted(threads(), key = lambda thread: thread.name):
		print "<tr><td>%s</td><td>" % ('None' if thread.ident is None else "%x" % abs(thread.ident))
		print thread.name
		print "<br>"
		try:
			print CollapsibleBox('Traceback', formatTrace(traceback.extract_stack(sys._current_frames()[thread.ident])))
		except Exception:
			pass
		print "</td><td class=\"%s\">&nbsp;</td><td class=\"%s\">&nbsp;</td></tr>" % ('yes' if thread.isAlive() else 'no', 'yes' if thread.daemon else 'no')
	print "</table>"

	print "<h3>Locks</h3>"
	print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"
	print "<tr><th class=\"main\">Name</th><th>Available</th><th>Reentrant</th></tr>"
	for (name, lock) in sorted(locks.iteritems()):
		print "<tr><td>"
		print name
		avail = lock.avail()
		if not avail:
			print "<br>"
			writer = ResponseWriter()
			try:
				owner, tb = lock.owner, lock.tb
				name = ("%x" % abs(owner)) if owner else 'None'
				#TODO Is there no O(1) way to do this?
				for thread in threads():
					if thread.ident == owner:
						name = "%s (%x)" % (thread.name, abs(owner))
						break
				print "Owned by: <b>%s</b><br><br>" % name
				if tb:
					print "Acquisition traceback:<br>"
					print formatTrace(tb)
					print "<br>"
				print "Current traceback:<br>"
				print formatTrace(traceback.extract_stack(sys._current_frames()[owner]))
			except Exception, e:
				writer.clear()
				print "<i>(Unable to retrieve stack trace)</i>"
			print CollapsibleBox('Ownership', writer.done())
		print "</td><td class=\"%s\">%s</td><td class=\"%s\">&nbsp;</td></tr>" % ('yes' if avail else 'no', '&nbsp;' if avail else (lock.owner or '???'), 'yes' if lock.reentrant() else 'no')
开发者ID:mrozekma,项目名称:Sprint,代码行数:59,代码来源:admin.py


示例18: log

 def log(self, message):
     try:
         file_name = traceback.extract_stack(limit=2)[0][0].split("DistributedSocialNetworking/", 1)[1]
         line = traceback.extract_stack(limit=2)[0][1]
         trace = "\n\n" + "    line: " + str(line) + " in " + file_name + "\n"
         self.logger.debug(trace + "    Message: " + message + "\n")
     except:
         self.logger.debug("\n\n Error while logging message.\n")
开发者ID:Roshack,项目名称:cmput410-project,代码行数:8,代码来源:utilites.py


示例19: zero_division_no_error

def zero_division_no_error(app):
    try:
        very_nested_zero_division_no_error(app)
    except ZeroDivisionError:
        pass
    exc_info_1 = sys.exc_info()
    traceback.extract_stack()
    return 'ha!'
开发者ID:jalvz,项目名称:fragile,代码行数:8,代码来源:__init__.py


示例20: enumerate_thread_trace

def enumerate_thread_trace(thread=None):
    if thread is None:
        stack = traceback.extract_stack()
    else:
        frame = sys._current_frames()[thread if isinstance(thread, int) else thread.ident]
        stack = traceback.extract_stack(frame)
    for path, line, function, statement in stack:
        yield clarify_source_path(path), line, function, statement
开发者ID:VDOMBoxGroup,项目名称:runtime2.0,代码行数:8,代码来源:tracing.py



注:本文中的traceback.extract_stack函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python traceback.extract_tb函数代码示例发布时间:2022-05-27
下一篇:
Python traceback._format_exc函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap