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

Python thread.get_ident函数代码示例

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

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



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

示例1: Checkout

def Checkout(tag,
             module_list,
             repository_name = "",
             az = None,
             timestamp = None,
             nonrecursive = 0,
             zap = None):

    log.trace( 'entry' , [ module_list , repository_name , az , timestamp , nonrecursive , zap ] )
    module_list = listify(module_list)

    if cvs_checkout_hook:
        module_list = cvs_checkout_hook(tag, module_list, repository_name, az, timestamp, nonrecursive)

    if not module_list:
        return

    if zap:
        for mod in module_list:
            if az:
                mod = az
            if os.path.exists(mod):
                import thread
                print "DELETING: %s [%d] START" % (mod, thread.get_ident())
                shell.rm(mod)
                print "DELETING: %s [%d] END" % (mod, thread.get_ident())
    
    log.trace( 'exit' )
    return Get(repository_name).Checkout(tag, module_list, az, timestamp, nonrecursive)
开发者ID:muromec,项目名称:qtopia-ezx,代码行数:29,代码来源:cvs.py


示例2: getValue

        def getValue(key):
            """Get the dynamic value of `key`"""
            try:
                value = values[key]

            except KeyError:
                this_thread = get_ident()
                rule = getRule(key)     # this ensures distances[key] is known

                stack = set_stack(this_thread, [])
                stack.append(distances[key])

                try:
                    value = key.__apply__(key, rule)
                finally:
                    distance = stack.pop()
                    if not stack:
                        del computing[this_thread]
                    else:
                        stack[-1] = min(stack[-1], distance)

                value = publish(distance, key, value)

            else:
                if computing:
                    stack = get_stack(get_ident())
                    if stack:
                        stack[-1] = min(stack[-1], distances[key])

            return value
开发者ID:jackie-qiu,项目名称:bambou,代码行数:30,代码来源:context.py


示例3: append

    def append(self, item, pys=False):
        """
        Call to add an object to the game world from threads outside the game loop
        """
        logging.debug("Append Object to World %s [%d]", repr(item), thread.get_ident())
        for objListener in self.__objectListener:
            objListener(item, True)

        logging.debug("SEMAPHORE ACQ append [%d]", thread.get_ident())
        self.__addremovesem.acquire()
        if not self.__objects.has_key(item.id):
            self.__objects[item.id] = item
            if pys:
                item.addToSpace(self.__space)
            elif item in self.__toremove:
                self.__toremove.remove(item)
            else:
                self.__toadd.append(item)

            if isinstance(item, Planet) and not item in self.__planets and item.pull > 0:
                self.__planets.append(item)
            elif isinstance(item, Nebula) and not item in self.__nebulas and item.pull > 0:
                self.__nebulas.append(item)
        self.__addremovesem.release()
        logging.debug("SEMAPHORE REL append [%d]", thread.get_ident())                
开发者ID:oshoukry,项目名称:SpaceBattleArena,代码行数:25,代码来源:WorldMap.py


示例4: do_post

 def do_post(self, url, u, request, settings={}, https=True):
     u = u.replace(" ", "%20")
     if DEBUG:
         logging.debug("*** POST *** (thr: %s, t: %s) %s" % (thread.get_ident(), ` int(time.time()) `, url + u))
     else:
         logging.info("*** POST *** %s" % url + u)
     params = self.anystring_as_utf8(request)
     if params:
         logging.debug("params: %s" % params)
     api_qa_cert = os.getenv("PYTAF_HOME") + "/resources/cert.pem"
     CERT_FILE = settings.get("cert_file", api_qa_cert)  # os.getenv("TEST_HOME") + "/resources/cert.pem"
     headers = self.get_headers(url, request, settings)
     logging.info("headers = %s:" % headers)
     if https == True:
         conn = httplib.HTTPSConnection(url, cert_file=CERT_FILE)
     else:
         conn = httplib.HTTPConnection(url)
     start_time = time.time()
     conn.request("POST", u, params, headers)
     response = conn.getresponse()
     end_time = time.time()
     logging.debug("%s, %s" % (response.status, response.reason))
     logging.debug(
         "http response time: (thr: %s, t: %s)" % (thread.get_ident(), round(float(end_time - start_time), 2))
     )
     d = response.read().decode()  # read() returns a bytes object
     logging.debug("%s" % d)
     return {"data": d, "status": response.status, "reason": response.reason}
开发者ID:tlichtenberg,项目名称:pytaf26,代码行数:28,代码来源:apilib.py


示例5: handle

    def handle(self):
        """Handle the communication."""

        print 'Accepting the connection %x from %s:%d' % (
            thread.get_ident(),
            self.request.getpeername()[0],
            self.request.getpeername()[1])

        self.request.settimeout(30)
        try:
            try:
                rbuffer = self.request.recv(1024)
            except socket.timeout:
                print 'The connection %s timed out - closing' % thread.get_ident()
                try:
                    self.request.close()
                except:
                    pass
                return
            else:
                sbuffer = self.session.process(rbuffer)
                self.request.sendall(sbuffer)
        except Exception, e:
            try:
                self.request.close()
            except:
                pass
            print '%s.\nConnection %x closed' % (e, thread.get_ident())
            return
开发者ID:Strongc,项目名称:lintouch,代码行数:29,代码来源:LintouchCommServer.py


示例6: handle

    def handle(self, *args, **options):
        self.build_id = 'build-%s' % now

        # send the end signal
        signals.build_item_commence.send(sender=self, thread=thread.get_ident())

        generate_screenshot = True if options['generate'] in ['True',True] else False
        all_pages = True if options['all'] in ['True',True] else False

        num_pages_ids = len(args)
        logger.debug('num num_pages_ids %d' % num_pages_ids)

        if all_pages in ['False',False] and num_pages_ids == 0:
            raise CommandError('Please specify page_id(s) to test in form: tailor_run_layout_test <id> <id> <id> ...')

        self.spindle = Spindle(capture=generate_screenshot, output_path=OUTPUT_PATH)

        if all_pages == True:
            args = []
            for page in Page.objects.all():
                self.test_page(url=page.url, elements_list=page.get_test_elements(), page=page)
        else:
            for page_id in args:
                try:
                    page = Page.objects.get(pk=int(page_id))
                except Page.DoesNotExist:
                    raise CommandError('Page "%s" does not exist' % page_id)

                self.test_page(url=page.url, elements_list=page.get_test_elements(), page=page)

        self.spindle.driver.close()
        self.spindle.driver.quit()

        # send the end signal
        signals.build_item_complete.send(sender=self, thread=thread.get_ident())
开发者ID:rosscdh,项目名称:schneiderlein,代码行数:35,代码来源:tailor_run_layout_test.py


示例7: ParallelThread

    def ParallelThread():
      for _ in xrange(self.OPEN_WITH_LOCK_TRIES_PER_THREAD):
        t = time.time()
        try:
          with aff4.FACTORY.OpenWithLock(
              self.client_urn, token=self.token, blocking=True,
              blocking_sleep_interval=self.OPEN_WITH_LOCK_SYNC_LOCK_SLEEP,
              blocking_lock_timeout=10):

            # We fail if another thread has the object already opened here.
            if self.opened:
              self.open_failures += 1
              self.fail("Double open!")

            self.opened = True
            logging.info("Thread %s holding lock for 0.5 seconds.",
                         thread.get_ident())
            time.sleep(0.5)

            # We fail if someone has closed the object while we are holding it
            # opened.
            if not self.opened:
              self.close_failures += 1
              self.fail("Double close!")

            self.results.append(thread.get_ident())

            self.opened = False
            return

        except aff4.LockError:
          logging.info("Lock failed after %s seconds - retying.",
                       (time.time() - t))
开发者ID:pombredanne,项目名称:grr-insider,代码行数:33,代码来源:data_store_test.py


示例8: acquire

    def acquire(self, flag=1):
        """Acquire the lock.

        If the optional flag argument is false, returns immediately
        when it cannot acquire the __wait lock without blocking (it
        may still block for a little while in order to acquire the
        __mutex lock).

        The return value is only relevant when the flag argument is
        false; it is 1 if the lock is acquired, 0 if not.

        """
        self.__mutex.acquire()
        try:
            if self.__tid == thread.get_ident():
                self.__count = self.__count + 1
                return 1
        finally:
            self.__mutex.release()
        locked = self.__wait.acquire(flag)
        if not flag and not locked:
            return 0
        try:
            self.__mutex.acquire()
            assert self.__tid == None
            assert self.__count == 0
            self.__tid = thread.get_ident()
            self.__count = 1
            return 1
        finally:
            self.__mutex.release()
开发者ID:Claruarius,项目名称:stblinux-2.6.37,代码行数:31,代码来源:Synch.py


示例9: get_session

    def get_session(self, session_id=''):
        """Return an existing or new client Session."""
        logger.debug("LOOKING FOR SESSION %s" % session_id)
        exists = self.sessions.session_exists(session_id)
        if exists:
            logger.debug('session exists')
        else:
            logger.debug('session does not exist')
            logger.debug('existing sessions are %s' \
                    % self.sessions.get_session_ids())

        session = self.sessions.get(session_id)

        if session is None:
            logger.debug("session doesn't exist locally")
            session = self.sessions.add_session(self)
            logger.debug("Thread %s - created session %s" % (get_ident(),
                                                      str(session)))
            if exists:
                session.incr_hits()
        else:
            logger.debug("Thread %s - reusing same session %s" % (get_ident(),
                                                           str(session)))
            session.incr_hits()

        return session
开发者ID:Natim,项目名称:redbarrel,代码行数:26,代码来源:servers.py


示例10: get_user_info_from_ldap

def get_user_info_from_ldap(nickname="", email="", ccid=""):
    """Query the CERN LDAP server for information about a user.
    Return a dictionary of information"""
    try:
        connection = _ldap_connection_pool[get_ident()]
    except KeyError:
        connection = _ldap_connection_pool[get_ident()] = _cern_ldap_login()
    if nickname:
        query = '(displayName=%s)' % nickname
    elif email:
        query = '(mail=%s)' % email
    elif ccid:
        query = '(employeeID=%s)' % ccid
    else:
        return {}
    try:
        result = connection.search_st(CFG_CERN_LDAP_BASE, ldap.SCOPE_SUBTREE, query,  timeout=5)
        if result and nickname:
            return result
        else:
            try:
                return result[0][1]
            except IndexError:
                return {}
    except ldap.TIMEOUT:
        pass
    return {}
开发者ID:pombredanne,项目名称:invenio,代码行数:27,代码来源:bibcirculation_cern_ldap.py


示例11: execute

 def execute(self, *args, **kwargs):
   global db
   if debug_cursors and self.c in c_closed:
     print >> param.log, 'INVALID CURSOR USE FOR %r' % self.c
     print >> param.log, 'Cursor alloc call was in:\n'
     print >> param.log, '-' * 78
     print >> param.log, ''.join(c_opened[self.c])
     print >> param.log, 'Cursor close call was in:\n'
     print >> param.log, '-' * 78
     print >> param.log, ''.join(c_closed[self.c])
   # SQLite3 can deadlock when multiple writers collide, so we use a lock to
   # prevent this from happening
   if args[0].split()[0].lower() in ['insert', 'update', 'delete', 'create'] \
          and not self.locked:
     db.acquire()
   before = time.time()
   if param.debug:
     print >> param.log, thread.get_ident(), time.time(), args
   backoff = 0.1
   done = False
   while not done:
     try:
       result = self.c.execute(*args, **kwargs)
       done = True
     except sqlite.OperationalError, e:
       if param.debug:
         print >> param.log, thread.get_ident(), time.time(), str(e),
         print >> param.log, 'sleeping for', backoff
       time.sleep(backoff)
       backoff = min(backoff * 2, 5.0)
开发者ID:fazalmajid,项目名称:temboz,代码行数:30,代码来源:singleton.py


示例12: begin_txn

    def begin_txn(self):
        """
        Start a bsddb transaction. If the current thread already has a running
        transaction, a nested transaction with the first transaction for this
        thread as parent is started. See:
        http://pybsddb.sourceforge.net/ref/transapp/nested.html for more on
        nested transactions in BDB.
        """
        # A user should be able to wrap several operations in a transaction.
        # For example, two or more adds when adding a graph.
        # Each internal operation should be a transaction, e.g. an add
        # must be atomic and isolated. However, since add should handle
        # BDB exceptions (like deadlock), an internal transaction should
        # not fail the user transaction. Here, nested transactions are used
        # which have this property.
        
        txn = None

        try:
            if not thread.get_ident() in self.__dbTxn and self.is_open() and not self.__closing:
                self.__dbTxn[thread.get_ident()] = []
                # add the new transaction to the list of transactions
                txn = self.db_env.txn_begin()
                self.__dbTxn[thread.get_ident()].append(txn)
            else:
                # add a nested transaction with the top one as parent
                txn = self.db_env.txn_begin(self.__dbTxn[thread.get_ident()][0])
                self.__dbTxn[thread.get_ident()].append(txn)
        except Exception, e:
            print "begin_txn: ", e
            if txn != None:
                txn.abort()
开发者ID:edsu,项目名称:mediatypes,代码行数:32,代码来源:BerkeleyDB.py


示例13: testDoubleCallbackToPython

 def testDoubleCallbackToPython(self):
     """Test a call to managed code that then calls back into Python
        that then calls managed code that then calls Python again."""
     dprint("thread %s DoubleCallBack" % thread.get_ident())
     result = ThreadTest.CallEchoString2("spam")
     self.failUnless(result == "spam")
     dprint("thread %s DoubleCallBack ret" % thread.get_ident())
开发者ID:ForrestFeng,项目名称:pythonnet,代码行数:7,代码来源:test_thread.py


示例14: run

    def run(self):
        """

        """
        if not self.head:
            while True:
                # if a worker is head it should not has
                # consume method, vise versa.
                # hence the if here sees to be redundant
                # 

                # if block at consume func, working is False.
                
                # TODO: self.working is a critical area. make it
                # atomic. 
                item = self.consume()
                logging.info(' %d: start working' % thread.get_ident())
                self.working = True
                ret = self.func(item)
                if not self.produce is None:
                    self.produce(ret)
                self.working = False
                logging.info(' %d: end working' % thread.get_ident())

        else:
            if not self.produce is None:
                for item in self.func():
                    self.produce(item)
开发者ID:bruceSz,项目名称:sflow_agent,代码行数:28,代码来源:utils.py


示例15: __delitem__

    def __delitem__(self, key, pys=False):
        logging.debug("Removing Object from World %s [%d]", repr(key), thread.get_ident())
        # Notify each item this may be in that it's no longer colliding
        # HACK: Get around issue with PyMunk not telling us shapes when object removed already before separate callback
        if len(key.in_celestialbody) > 0:
            for item in key.in_celestialbody[:]:
                item.collide_end(key)

        logging.debug("SEMAPHORE ACQ delitem [%d]", thread.get_ident())
        self.__addremovesem.acquire()            
        if self.__objects.has_key(key.id):
            if pys:
                key.removeFromSpace(self.__space)
            elif key in self.__toadd:
                self.__toadd.remove(key)
            else:
                self.__toremove.append(key)
            
            del self.__objects[key.id]
            if key in self.__influential:
                self.__influential.remove(key)
        self.__addremovesem.release()           
        logging.debug("SEMAPHORE REL delitem [%d]", thread.get_ident())
        
        # Notify after removed, in case re-add same object
        for objListener in self.__objectListener:
            objListener(key, False)
开发者ID:Mikeware,项目名称:SpaceBattleArena,代码行数:27,代码来源:WorldMap.py


示例16: run

 def run(self):
     print "run"
     while 1:
         self.emit("now", "now", str(thread.get_ident()))
         GObject.idle_add(self.emit, "idle", "idle",
                          str(thread.get_ident()))
         time.sleep(1)
开发者ID:bossjones,项目名称:scarlett-dbus-poc,代码行数:7,代码来源:emit.py


示例17: save_data

    def save_data(self, environ, start, stop, collector):
        data = {}
        data['hostname'] = self.hostname
        data['environ'] = dict((k, v) for k, v in environ.iteritems() if isinstance(v, basestring))
        data['start_time'] = start
        data['stop_time'] = stop
        data['thread_ident'] = thread.get_ident()
        # Only take the 25 most frequent stack frames
        collector.filter(25)

        samples = []
        for stack, frequency in collector.stack_counts.iteritems():
            frames = []
            for elm in stack:
                frame = {}
                frame['file'] = elm[0]
                frame['line_no'] = elm[1]
                frame['function'] = elm[2]
                frames.append(frame)

            sample = {}
            sample['frames'] = frames
            sample['frequency'] = frequency
            samples.append(sample)

        data['samples'] = samples

        filename = '%s-%s' % (time.time(), thread.get_ident())

        if not os.path.exists(self.outpath):
            os.makedirs(self.outpath)

        with open(os.path.join(self.outpath, filename + '.json'), 'w') as fp:
            json.dump(data, fp, indent=2)
开发者ID:disqus,项目名称:plop,代码行数:34,代码来源:wsgi.py


示例18: stemWords

 def stemWords(words, lang):
     """Return WORDS stemmed according to language LANG (e.g. 'en')."""
     if lang == 'en' and _stemmers and _stemmers.has_key(get_ident()):
         #make sure _stemmers[get_ident()] is avail..
         return [_stemmers[get_ident()].stem(word, 0, len(word)-1) for word in words]
     else:
         return words
开发者ID:lbjay,项目名称:cds-invenio,代码行数:7,代码来源:bibindex_engine_stemmer.py


示例19: lookup

 def lookup(key):
     """Return the value of `key` in the current state"""
     try:
         state, getRule, lookup, child = states[get_ident()]
     except KeyError:
         empty().swap()
         state, getRule, lookup, child = states[get_ident()]
     return lookup(key)
开发者ID:jackie-qiu,项目名称:bambou,代码行数:8,代码来源:context.py


示例20: GetActivityIds

	def GetActivityIds(self):
		if len(self.activities) == 0:
			self.RetrieveActivities()
			if len(self.activities) == 0:
				self.logger.error("[{i}] [{t}] [{f}] ({m})".format(i=self.id, t=thread.get_ident(), f=str(sys._getframe().f_code.co_name), m="No activities for this account"))
				raise NikePlusError("There are no activities for this account")
		self.logger.debug("[{i}] [{t}] [{f}] ({m})".format(i=self.id, t=thread.get_ident(), f=str(sys._getframe().f_code.co_name), m=str(self.activities.keys())))
		return self.activities.keys()
开发者ID:rhysmccaig,项目名称:blue-ribbon-plus,代码行数:8,代码来源:nikeplus.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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