本文整理汇总了Python中traceback.extract_stack函数的典型用法代码示例。如果您正苦于以下问题:Python extract_stack函数的具体用法?Python extract_stack怎么用?Python extract_stack使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了extract_stack函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()))
示例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
示例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)
示例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
示例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
示例6: main
def main():
print'begin' #如果这里不捕捉异常的话,程序运行到打印出begin就结束了,final是不会被打印的
try:
sys.exit('exitok')
except :
print traceback.extract_stack()
print'final'
示例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
示例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)
示例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))
示例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
示例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'))
示例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
示例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()
示例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()
示例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()