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

Python traceback.print_stack函数代码示例

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

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



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

示例1: cry

def cry(out=None, sepchr='=', seplen=49):  # pragma: no cover
    """Return stack-trace of all active threads,
    taken from https://gist.github.com/737056."""
    import threading

    out = WhateverIO() if out is None else out
    P = partial(print, file=out)

    # get a map of threads by their ID so we can print their names
    # during the traceback dump
    tmap = {t.ident: t for t in threading.enumerate()}

    sep = sepchr * seplen
    for tid, frame in items(sys._current_frames()):
        thread = tmap.get(tid)
        if not thread:
            # skip old junk (left-overs from a fork)
            continue
        P('{0.name}'.format(thread))
        P(sep)
        traceback.print_stack(frame, file=out)
        P(sep)
        P('LOCAL VARIABLES')
        P(sep)
        pprint(frame.f_locals, stream=out)
        P('\n')
    return out.getvalue()
开发者ID:277800076,项目名称:celery,代码行数:27,代码来源:__init__.py


示例2: get_prefix

    def get_prefix(self, ns):
        """Returns the prefix assigned to a namespace

        ns
            The namespace URI as a character string.

        Returns None if no prefix is currently in force for this
        namespace."""
        if ns == XML_NAMESPACE:
            return "xml"
        elif ns is None:
            # Attributes with no namespace
            logging.error("Deprecation warning: None for ns")
            import traceback

            traceback.print_stack()
            return ""
        elif ns == NO_NAMESPACE:
            return ""
        prefix = None
        ei = self
        while prefix is None and ei is not None:
            prefix = ei._ns_to_prefix.get(ns, None)
            if prefix is not None:
                # this is the prefix to use, unless it has been reused...
                ej = self
                while ej is not ei:
                    if ej._prefix_to_ns.get(prefix, None) is not None:
                        # so prefix has been reused, keep searching
                        prefix = None
                        break
                    ej = ej.parent
            ei = ei.parent
        return prefix
开发者ID:ianwj5int,项目名称:pyslet,代码行数:34,代码来源:namespace.py


示例3: log

def log(level, *args):
  if level <= verbosity:
    prefix = str(level) + ": "
    print >> sys.stderr, prefix + "".join(map(str, args))
  if level == Level.Fatal:
    traceback.print_stack()
    sys.exit(1)
开发者ID:likan999,项目名称:archiver,代码行数:7,代码来源:archiver.py


示例4: cry

def cry():  # pragma: no cover
    """Return stacktrace of all active threads.

    From https://gist.github.com/737056

    """
    tmap = {}
    main_thread = None
    # get a map of threads by their ID so we can print their names
    # during the traceback dump
    for t in threading.enumerate():
        if getattr(t, "ident", None):
            tmap[t.ident] = t
        else:
            main_thread = t

    out = StringIO()
    sep = "=" * 49 + "\n"
    for tid, frame in sys._current_frames().iteritems():
        thread = tmap.get(tid, main_thread)
        out.write("%s\n" % (thread.getName(),))
        out.write(sep)
        traceback.print_stack(frame, file=out)
        out.write(sep)
        out.write("LOCAL VARIABLES\n")
        out.write(sep)
        pprint(frame.f_locals, stream=out)
        out.write("\n\n")
    return out.getvalue()
开发者ID:ackdesha,项目名称:celery,代码行数:29,代码来源:__init__.py


示例5: full_trace

def full_trace(f, *args, **kw):
    if param.debug:
        print '** Debugging info **'
        traceback.print_stack()
        print "Calling %s with args %s, %s" % (f.func_name, args, kw)
        print '-------------------\n'
    return f(*args, **kw)
开发者ID:Grahack,项目名称:geophar,代码行数:7,代码来源:fonctions.py


示例6: prop_get

def prop_get(target, key, type, ignore_errors=False):
    if isinstance(type, list):
        scalar_type = type[0]
    else:
        scalar_type = type
    (pytype, atom, format, serialize, deserialize, terminator) = _prop_types[scalar_type]
    try:
        #print(atom)
        data = trap.call_synced(XGetWindowProperty, target, key, atom)
        #print(atom, repr(data[:100]))
    except NoSuchProperty:
        log.debug("Missing property %s (%s)", key, type)
        return None
    except (XError, PropertyError):
        if not ignore_errors:
            log.info("Missing window or missing property or wrong property type %s (%s)", key, type)
            import traceback
            traceback.print_stack()
        return None
    try:
        return _prop_decode(target, type, data)
    except:
        log.warn("Error parsing property %s (type %s); this may be a"
                 + " misbehaving application, or bug in Wimpiggy\n"
                 + "  Data: %r[...?]",
                 key, type, data[:160])
        raise
开发者ID:svn2github,项目名称:Xpra,代码行数:27,代码来源:prop.py


示例7: generate_page

	def generate_page(self):
		try:
			f1 = open(self.template_page, "r")
			self.results = self.check_for_input()
			f2 = open(self.inventory_file, "r")
			self.stuff = f2.read().strip().split(", ")
			pickup_form_stuff = self.pickup_form()
			drop_form_stuff = self.drop_form()
			go_left_stuff = self.go_form('&larr;Go Left', 'left', 'http://cs.mcgill.ca/~pcrane/teamPage/cgi-bin/show.py')
			go_right_stuff = self.go_form('Go Right&rarr;', 'right', 'http://cs.mcgill.ca/~jmahen/cgi-bin/show.py')
			if self.loyalty == "none" or self.loyalty == "":
				self.loyalty = "none. <span class='error'>Move left to choose a side.</span>"
			print f1.read() % (pickup_form_stuff, drop_form_stuff, self.what_i_have, self.picked_up, self.dropped, self.loyalty, self.points, go_left_stuff['link'], go_right_stuff['link'], go_left_stuff['output'], go_right_stuff['output'])
		except Exception, e:
			import traceback, sys
			print
			print '<html><head><title>'
			print str(e)
			print '</title>'
			print '</head><body>'
			print '<h1>TRACEBACK</h1>'
			print '<pre>'
			print str(e)
			traceback.print_exc()
			traceback.print_stack()
			print "Unexpected error:", sys.exc_info()[0]
			print '</pre>'
			print '</body></html>'
开发者ID:parkr,项目名称:Angels-vs-Demons,代码行数:28,代码来源:activity.py


示例8: execute

def execute(meth, *args, **kwargs):
    """
    Execute *meth* in a Python thread, blocking the current coroutine/
    greenthread until the method completes.

    The primary use case for this is to wrap an object or module that is not
    amenable to monkeypatching or any of the other tricks that Eventlet uses
    to achieve cooperative yielding.  With tpool, you can force such objects to
    cooperate with green threads by sticking them in native threads, at the cost
    of some overhead.
    """
    setup()
    # if already in tpool, don't recurse into the tpool
    # also, call functions directly if we're inside an import lock, because
    # if meth does any importing (sadly common), it will hang
    my_thread = threading.currentThread()
    if my_thread in _threads or imp.lock_held() or _nthreads == 0:
        return meth(*args, **kwargs)

    e = event.Event()
    _reqq.put((e, meth, args, kwargs))

    rv = e.wait()
    if isinstance(rv, tuple) \
            and len(rv) == 3 \
            and isinstance(rv[1], EXC_CLASSES):
        (c, e, tb) = rv
        if not QUIET:
            traceback.print_exception(c, e, tb)
            traceback.print_stack()
        six.reraise(c, e, tb)
    return rv
开发者ID:Aayush-Kasurde,项目名称:eventlet,代码行数:32,代码来源:tpool.py


示例9: process_error

def process_error(error, vic_exe):
    '''Helper function to process possible error raised during testing'''
    tail = None
    if isinstance(error, VICRuntimeError):
        test_comment = 'Test failed during simulation'
        tail = vic_exe.stderr
    elif isinstance(error, VICTestError):
        test_comment = 'Test failed during testing of output files'
    elif isinstance(error, VICValgrindError):
        test_comment = 'Test failed due to memory error detected by valgrind'
        tail = vic_exe.stderr
    elif isinstance(error, VICReturnCodeError):
        test_comment = 'Test failed due to incorrect return code'
        tail = vic_exe.stderr
    elif isinstance(error, AssertionError):
        test_comment = 'AssertionError raised during testing'
    else:
        test_comment = 'Unknown test failure'
        traceback.print_stack()

    print('\t{0}'.format(test_comment))
    print('\t{0}'.format(error))
    if tail is not None:
        print('\tLast {0} lines of standard out:'.format(ERROR_TAIL))
        print_tail(tail, n=ERROR_TAIL)

    return test_comment, error
开发者ID:BramDr,项目名称:VIC,代码行数:27,代码来源:test_utils.py


示例10: cry

def cry():  # pragma: no cover
    """Return stacktrace of all active threads.

    From https://gist.github.com/737056

    """
    tmap = {}
    main_thread = None
    # get a map of threads by their ID so we can print their names
    # during the traceback dump
    for t in threading.enumerate():
        if getattr(t, 'ident', None):
            tmap[t.ident] = t
        else:
            main_thread = t

    out = StringIO()
    P = partial(print, file=out)
    sep = '=' * 49
    for tid, frame in sys._current_frames().iteritems():
        thread = tmap.get(tid, main_thread)
        if not thread:
            # skip old junk (left-overs from a fork)
            continue
        P('{0.name}'.format(thread))
        P(sep)
        traceback.print_stack(frame, file=out)
        P(sep)
        P('LOCAL VARIABLES')
        P(sep)
        pprint(frame.f_locals, stream=out)
        P('\n')
    return out.getvalue()
开发者ID:KWMalik,项目名称:celery,代码行数:33,代码来源:__init__.py


示例11: writeLog

        def writeLog(logLevel,logMessage):
#                alogLevel = ["trace","warning","error"]
                sExceptMsg = ""
                if Config.B_SYS_DEBUG:
                    sExceptMsg += "\r\n**********************%s %s*********************************\r\n"%(logLevel.upper(),Func.fNow())
                    sExceptMsg += "\r\n%s Messages:%s"%(logLevel.upper(),str(logMessage))
                    sExceptMsg += "\r\n"
                if logLevel=="trace":
                        if Config.B_SYS_WRITE_LOG:
                                logger = LogInfo.initlog()
                                logger.info(logMessage)
                        if Config.B_SYS_TRACE:
                                print "\r\nTrace stack is flow:\r\n"
                                traceback.print_stack()
                                print "\r\n"                
                elif logLevel=="warning":
                        pass
                elif logLevel=="error":
                        exc_type, exc_value, exc_traceback = sys.exc_info()
                        if exc_type!=None:
                                sExceptMsg += "\r\n"
                                sExceptMsg += repr(traceback.format_tb(exc_traceback))
                                sExceptMsg += "\r\n"
                        else:
                                print "\r\nTrace stack is flow:\r\n"
                                traceback.print_stack()
                                sExceptMsg += "\r\n"
                         
                        if Config.B_SYS_WRITE_LOG and exc_type!=None:
                                logger = LogInfo.initlog()
                                logger.error(sExceptMsg)
                if Config.B_SYS_DEBUG:
                    sExceptMsg += "\r\n*********************%s END**********************************\r\n"%(logLevel.upper())
                    print   sExceptMsg      
开发者ID:geminiblue,项目名称:oliyoapiserver,代码行数:34,代码来源:LogInfo.py


示例12: _show_tab

	def _show_tab(self, number):
		"""Used as callback function for the TabButtons.
		@param number: tab number that is to be shown.
		"""
		if not number in range(len(self._tabs)):
			# this usually indicates a non-critical error, therefore we can handle it without crashing
			traceback.print_stack()
			self.log.warning("Invalid tab number %s, available tabs: %s", number, self._tabs)
			return
		if self.current_tab.is_visible():
			self.current_tab.hide()
		new_tab = self._tabs[number]
		old_bg = self.content.findChild(name = "bg_%s" % self._tabs.index(self.current_tab))
		old_bg.image = self.current_tab.button_background_image
		name = str(self._tabs.index(self.current_tab))
		old_button = self.content.findChild(name=name)
		old_button.path = self.current_tab.path

		new_bg = self.content.findChild(name = "bg_%s" % number)
		new_bg.image = self.current_tab.button_background_image_active
		new_button = self.content.findChild(name=str(number))
		new_button.path = new_tab.path_active
		self.current_tab = new_tab
		# important to display the tabs correctly in front
		self.widget.hide()
		self.show()

		self._apply_layout_hack()
开发者ID:STEVEOO6,项目名称:unknown-horizons,代码行数:28,代码来源:tabwidget.py


示例13: submit_job

    def submit_job(self, job):
        id = uuid.uuid1()
        job['id'] = id
        print("Job %s created %s" % (job['id'], job['created'].strftime('%Y.%m.%d %H:%M:%S')))
        create_job_in_db(job)

        # put job in queue
        try:
            q.put(job, block=False)
        except Full as e:
            traceback.print_stack()
            traceback.print_exc()
            update_job_status(job['id'], "error")
            raise

        # update status to queued
        try:
            q_len = q.qsize()
            if (q_len >= QUEUE_WARN_SIZE):
                adminEmailer.warn("Queue is getting too long. There are currently %d items in the queue." % q_len)
            update_job_status(job['id'], "queued", "queue length %d" % q_len)
        except NotImplementedError:
            print("q.qsize not supported")
            update_job_status(job['id'], "queued")
        return id
开发者ID:cbare,项目名称:miRvestigator_www,代码行数:25,代码来源:mirv_server.py


示例14: __setattr__

	def __setattr__(self, name, attr):
		real = typos.get(name, name)
		if real != name:
			warn('typo %s -> %s' % (name, real))
			if Logs.verbose > 0:
				traceback.print_stack()
		object.__setattr__(self, real, attr)
开发者ID:CodeMonk,项目名称:fish,代码行数:7,代码来源:TaskGen.py


示例15: acquire

 def acquire(self):
     print('#' * 120, file=sys.stderr)
     print('acquire called: thread id:', current_thread(), 'shared:', self._is_shared, file=sys.stderr)
     traceback.print_stack()
     RWLockWrapper.acquire(self)
     print('acquire done: thread id:', current_thread(), file=sys.stderr)
     print('_' * 120, file=sys.stderr)
开发者ID:j-howell,项目名称:calibre,代码行数:7,代码来源:locking.py


示例16: mousePressed

	def mousePressed(self, evt):
		if evt.isConsumedByWidgets():
			super(SelectionTool, self).mousePressed(evt)
			return
		elif evt.getButton() == fife.MouseEvent.LEFT:
			if self.session.selected_instances is None:
				# this is a very odd corner case, it should only happen after the session has been ended
				# we can't allow to just let it crash however
				self.log.error('Error: selected_instances is None. Please report this!')
				traceback.print_stack()
				self.log.error('Error: selected_instances is None. Please report this!')
				return
			instances = self.get_hover_instances(evt)
			self.select_old = frozenset(self.session.selected_instances) if evt.isControlPressed() else frozenset()

			instances = filter(self.is_selectable, instances)
			# On single click, only one building should be selected from the hover_instances.
			# The if is for [] and [single_item] cases (they crashed).
			# It acts as user would expect: instances[0] selects buildings in front first.
			instances = instances if len(instances) <= 1 else [instances[0]]

			self._update_selection(instances)

			self.select_begin = (evt.getX(), evt.getY())
			self.session.ingame_gui.hide_menu()
		elif evt.getButton() == fife.MouseEvent.RIGHT:
			target_mapcoord = self.get_exact_world_location(evt)
			for i in self.session.selected_instances:
				if i.movable:
					Act(i, target_mapcoord.x, target_mapcoord.y).execute(self.session)
		else:
			super(SelectionTool, self).mousePressed(evt)
			return
		evt.consume()
开发者ID:Octavianuspg,项目名称:unknown-horizons,代码行数:34,代码来源:selectiontool.py


示例17: release

 def release(self, *args):
     print('*' * 120, file=sys.stderr)
     print('release called: thread id:', current_thread(), 'shared:', self._is_shared, file=sys.stderr)
     traceback.print_stack()
     RWLockWrapper.release(self)
     print('release done: thread id:', current_thread(), 'is_shared:', self._shlock.is_shared, 'is_exclusive:', self._shlock.is_exclusive, file=sys.stderr)
     print('_' * 120, file=sys.stderr)
开发者ID:j-howell,项目名称:calibre,代码行数:7,代码来源:locking.py


示例18: _ldap_call

 def _ldap_call(self,func,*args,**kwargs):
   """
   Wrapper method mainly for serializing calls into OpenLDAP libs
   and trace logs
   """
   self._ldap_object_lock.acquire()
   if __debug__:
     if self._trace_level>=1:
       self._trace_file.write('*** %s %s - %s\n%s\n' % (
         repr(self),
         self._uri,
         '.'.join((self.__class__.__name__,func.__name__)),
         pprint.pformat((args,kwargs))
       ))
       if self._trace_level>=9:
         traceback.print_stack(limit=self._trace_stack_limit,file=self._trace_file)
   diagnostic_message_success = None
   try:
     try:
       result = func(*args,**kwargs)
       if __debug__ and self._trace_level>=2:
         if func.__name__!="unbind_ext":
           diagnostic_message_success = self._l.get_option(ldap.OPT_DIAGNOSTIC_MESSAGE)
     finally:
       self._ldap_object_lock.release()
   except LDAPError as e:
     if __debug__ and self._trace_level>=2:
       self._trace_file.write('=> LDAPError - %s: %s\n' % (e.__class__.__name__,str(e)))
     raise
   else:
     if __debug__ and self._trace_level>=2:
       if not diagnostic_message_success is None:
         self._trace_file.write('=> diagnosticMessage: %s\n' % (repr(diagnostic_message_success)))
       self._trace_file.write('=> result:\n%s\n' % (pprint.pformat(result)))
   return result
开发者ID:tiran,项目名称:pyldap,代码行数:35,代码来源:ldapobject.py


示例19: parse

def parse(data, file=None, create_logger=False, expand_loops=True, expand_generators=True):
    if file != None:
        glob.g_file = file

    if glob.g_add_newlines:
        data = add_newlines(data)
        # print(data[1017297])
        data = data.replace("\\n", "\n")
        for l in data.split("\n"):
            try:
                print(l)
            except UnicodeEncodeError:
                pass
        return data, StatementList()

    try:
        if glob.g_gen_es6:
            return parse_intern_es6(data)
        else:
            return parse_intern(
                data, create_logger=create_logger, expand_loops=expand_loops, expand_generators=expand_generators
            )
    except JSError:
        if glob.g_print_stack:
            traceback.print_stack()
            traceback.print_exc()

        glob.g_error = True
        return "", None
开发者ID:joeedh,项目名称:webblender,代码行数:29,代码来源:js_cc.py


示例20: parseJSON

def parseJSON(data, outFile, fileqcn, dbconn):                   # [1]
  ctr = 0
  try:
    json_data=open(FILE_USGS_JSON)
    data = simplejson.load(json_data)
    for item in data["features"]:
      ctr = ctr + 1 
      if ctr > 300:
         break
      sq.__init__()

      #print item['id'], item['properties']['time'],item['properties']['place'],item['properties']['mag'],item['properties']['url'],item['geometry']['coordinates'][0],item['geometry']['coordinates'][1],item['geometry']['coordinates'][2]

      sq.time = float(item['properties']['time'])/1000.0
      sq.strTime = datetime.fromtimestamp(int(sq.time)).strftime(TIME_PATTERN)
      sq.magnitude = float(item['properties']['mag'])
      sq.strDesc   = item['properties']['place']
      sq.strURL    = item['properties']['url']
      sq.latitude = float(item['geometry']['coordinates'][1])
      sq.longitude = float(item['geometry']['coordinates'][0])
      sq.strGUID = item['id']
      sq.depth_km = float(item['geometry']['coordinates'][2])
      sq.print_record(fileqcn, ctr, dbconn)
      sq.__init__()

    return ctr
  except:
    print "Error in parseJSON" + FILE_USGS_JSON
    traceback.print_stack()
    traceback.print_exc(file=sys.stdout)
    return -1
开发者ID:carlgt1,项目名称:qcn,代码行数:31,代码来源:parse-usgs-json.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python traceback.print_tb函数代码示例发布时间:2022-05-27
下一篇:
Python traceback.print_list函数代码示例发布时间: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