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

Python threading.enumerate函数代码示例

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

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



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

示例1: test_urlfetch_slow_server

    def test_urlfetch_slow_server(self):
        """The function also times out if the server replies very slowly.
        (Do the server part in a separate thread.)
        """
        sock, http_server_url = self.make_test_socket()
        sock.listen(1)
        stop_event = threading.Event()
        def slow_reply():
            (client_sock, client_addr) = sock.accept()
            content = 'You are veeeeryyy patient!'
            client_sock.sendall(dedent("""\
                HTTP/1.0 200 Ok
                Content-Type: text/plain
                Content-Length: %d\n\n""" % len(content)))

            # Send the body of the reply very slowly, so that
            # it times out in read() and not urlopen.
            for c in content:
                client_sock.send(c)
                if stop_event.wait(0.05):
                    break
            client_sock.close()
        slow_thread = threading.Thread(target=slow_reply)
        slow_thread.start()
        saved_threads = set(threading.enumerate())
        self.assertRaises(TimeoutError, urlfetch, http_server_url)
        # Note that the cleanup also takes care of leaving no worker thread behind.
        remaining_threads = set(threading.enumerate()).difference(saved_threads)
        self.assertEqual(set(), remaining_threads)
        stop_event.set()
        slow_thread.join()
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:31,代码来源:test_timeout.py


示例2: EnableHelloHueCallback

def EnableHelloHueCallback():
	Log("Trying to enable thread")
	#threading.Thread(target=run_websocket_watcher,name='thread_websocket').start()
	if not "thread_websocket" in str(threading.enumerate()):
		ValidatePrefs()
	Log(threading.enumerate())
	return MainMenu(header=NAME, message='HelloHue is now enabled.')
开发者ID:celestian02,项目名称:HelloHue,代码行数:7,代码来源:__init__.py


示例3: main

def main():
    #initial the database connection
    database = DB_helper.DB_helper("root", "900129lbb", "127.0.0.1", "Webscraping")
    csv = CSV_helper.CSV_helper()
    xml = XML_helper.XML_helper("Config.xml")

    threads = []
    brands = xml.read()

    for brand, v_b in brands.items():
        #every csv file is a brand
        thread = thread_handle(brand, v_b)
        thread.start()
        threads.append(thread)
        print len(threading.enumerate())
        while True:
            if (len(threading.enumerate()) < 10):
                break
            else:
                print "sleep"
                time.sleep(10)
    for thread in threads:
        thread.join()
    #combine every csv into one xls file,
    #every csv file name is the sheet name
    print "start merging"
    csv.csvs_to_excel()
开发者ID:linbinbin90,项目名称:ReportBuild,代码行数:27,代码来源:Multi_thread.py


示例4: _threadChecker

    def _threadChecker(self):
        while True:
            try:
                # for those :
                #     1. might request thread is closed
                #     2. cause by bug ...
                actives = set(thread.ident for thread in threading.enumerate())
                keepings = set(ident for ident in self._connections.keys())

                useless = keepings - actives
                if useless:
                    logging.warning('sqlpool : useless connection found (%d)' % len(useless))
                
                # release useless connection
                for ident in useless:
                    for thread in threading.enumerate():
                        if thread.ident == ident and thread.isAlive():
                            break
                    else:
                        self.__releaseConnection(ident)
            
            except Exception, e:
                logging.error('sqlpool error (_threadChecker) : %s' % str(e))
            
            finally:
开发者ID:zh3linux,项目名称:mysql2elasticsearch,代码行数:25,代码来源:sqlpool.py


示例5: shutdown

    def shutdown(self):
        BuiltinCore.shutdown(self)
        self.logger.info("Closing RPC command queues")
        self.rpc_q.close()

        def term_children():
            """ Terminate all remaining multiprocessing children. """
            for child in multiprocessing.active_children():
                self.logger.error("Waited %s seconds to shut down %s, "
                                  "terminating" % (self.shutdown_timeout,
                                                   child.name))
                child.terminate()

        timer = threading.Timer(self.shutdown_timeout, term_children)
        timer.start()
        while len(multiprocessing.active_children()):
            self.logger.info("Waiting for %s child(ren): %s" %
                             (len(multiprocessing.active_children()),
                              [c.name
                               for c in multiprocessing.active_children()]))
            time.sleep(1)
        timer.cancel()
        self.logger.info("All children shut down")

        while len(threading.enumerate()) > 1:
            threads = [t for t in threading.enumerate()
                       if t != threading.current_thread()]
            self.logger.info("Waiting for %s thread(s): %s" %
                             (len(threads), [t.name for t in threads]))
            time.sleep(1)
        self.logger.info("Shutdown complete")
开发者ID:Bcfg2,项目名称:bcfg2,代码行数:31,代码来源:MultiprocessingCore.py


示例6: ValidatePrefs

def ValidatePrefs():
	global auth, plex, hue, converter, active_clients, firstrun
	Log('Validating Prefs')
	auth = HueCheck().check_username()
	if auth is False:
		Log("Please update your Hue preferences and try again")
	if auth is True:
		Log("Hue username is registered... Starting!")
	converter = Converter()
	hue = Hue()
	CompileRooms()
	hue.get_hue_light_groups()
	InitiateCurrentStatus()
	plex = Plex()
	active_clients = []
	Log("Classes initiated")
	if "thread_websocket" in str(threading.enumerate()):
		Log("Closing daemon...")
		ws.close()
	if not "thread_websocket" in str(threading.enumerate()):
		Log("Starting websocket daemon...")
		threading.Thread(target=run_websocket_watcher,name='thread_websocket').start()
	if "thread_clients" in str(threading.enumerate()):
		Log("Setting firstrun to True")
		firstrun = True
	if not "thread_clients" in str(threading.enumerate()):
		Log("Starting clients daemon...")
		threading.Thread(target=watch_clients,name='thread_clients').start()
	Log(threading.enumerate())
	return MainMenu(header=NAME)
开发者ID:Be2daErtin,项目名称:HelloHue,代码行数:30,代码来源:__init__.py


示例7: __init__

    def __init__(self):
        self.points = 60
        self.living = True

        self.server = Server()
        self.spi = Spi(self.points)
        self.queueSize = 20
        self.proccessQueue = queue.Queue(self.queueSize)
        self.oscWindow_1 = []

        self.trigger = Trigger(1,-5)

        #Thread to handle reading from SPI then writing to Server
        spiThread = threading.Thread(target = self.spiRead)
        spiThread.name = "SPI_Thread"
        spiThread.deamon = True    #Kill off on its own
        spiThread.start()

        #Thread to handle reading from Server then writing to SPI
        serverThread = threading.Thread(target = self.serverRead)
        serverThread.name = "SERVER_Thread"
        serverThread.deamon = True
        serverThread.start()

        print(threading.active_count())
        for thrd in threading.enumerate():
            if(thrd.isDaemon):
                print(thrd)

        while(self.living):
            x= 0
        print(threading.active_count())
        for thrd in threading.enumerate():
            if(thrd.isDaemon):
                print(thrd)
开发者ID:Typhoone,项目名称:IEP,代码行数:35,代码来源:middleWare.py


示例8: finish

 def finish(self):
     self.hps.kill_watch_status()
     self.vps.kill_watch_status()
     self.logging_switch.clear()
     time.sleep(5)
     print "Tried to kill all threads. There are still ", threading.active_count(), " alive"
     threading.enumerate()
开发者ID:B2202,项目名称:automation,代码行数:7,代码来源:measurement_test.py


示例9: poll

 def poll(self):
     '''
     Check for events from SUMA.
     '''
     if self.proc_thread:
         if self.proc_thread not in threading.enumerate():
             tkMessageBox.showwarning("Connection to SUMA lost", 
                   "The connection to SUMA has been lost. "+
                   "Reload  your dataset to continue using COVI.")
             self.proc_not_ready()
             self.proc_thread = False
         if self.proc_thread and self.proc_thread.ready():
             try:
                 res = self.proc_thread.res_q.get_nowait()
                 self.proc_thread.res_q.task_done()
                 if res:
                     if res[0] == 'node':
                         self.node_number_label['text'] = '%i'%res[1]
                     elif res[0] == 'cluster':
                         self.cluster_number_label['text'] = '%i'%res[1]
                     elif res[0] == 'area':
                         self.curr_area_label['text'] = res[1]
                     elif res[0] == 'ready':
                         # Re-enable main window widgets
                         set_state(self.real_root, 'enabled')
             except Empty:
                 pass
     if self.net_thread and self.net_thread not in threading.enumerate():
         tkMessageBox.showwarning("Connection to server lost", 
               "The connection to the server has been lost. "+
               "Reload  your dataset to continue using COVI.")
         self.proc_not_ready()
         self.net_thread = False
     
     self.root.after(100, self.poll)
开发者ID:levmorgan,项目名称:COVIClient,代码行数:35,代码来源:COVI_Client.py


示例10: shutdown

def shutdown():
    from logs import lg
    from main import config
    from system import bpio
    lg.out(2, 'bpmain.shutdown')

    import shutdowner
    shutdowner.A('reactor-stopped')

    from automats import automat
    automat.objects().clear()
    if len(automat.index()) > 0:
        lg.warn('%d automats was not cleaned' % len(automat.index()))
        for a in automat.index().keys():
            lg.out(2, '    %r' % a)
    else:
        lg.out(2, 'bpmain.shutdown automat.objects().clear() SUCCESS, no state machines left in memory')

    config.conf().removeCallback('logs/debug-level')

    lg.out(2, 'bpmain.shutdown currently %d threads running:' % len(threading.enumerate()))
    for t in threading.enumerate():
        lg.out(2, '    ' + str(t))

    lg.out(2, 'bpmain.shutdown finishing and closing log file, EXIT')

    automat.CloseLogFile()

    lg.close_log_file()

    if bpio.Windows() and bpio.isFrozen():
        lg.stdout_stop_redirecting()

    return 0
开发者ID:vesellov,项目名称:bitdust.devel,代码行数:34,代码来源:bpmain.py


示例11: generate_poisson_spiketrains_task

def generate_poisson_spiketrains_task(rate, number_of_spiketrains, time):

    # Init result and output-hdf5_file
    # res = []

    # Init number of Semaphore
    s = threading.Semaphore(pool_size)

    local_data = threading.local()

    write_lock = threading.Lock()

    # pool = PoolActive()
    for i in range(number_of_spiketrains):
        t = threading.Thread(target=worker, name=str(i), args=(s, local_data,
                                                               write_lock,
                                                               rate,
                                                               time))
        t.start()

    # ----------- Joining , wait for all thread done ---------
    logging.debug('Waiting for worker threads')
    main_thread = threading.currentThread()
    print "Threading enumerate ", threading.enumerate()
    for t in threading.enumerate():
        if t is not main_thread:
            print "t = ", t.getName()
            t.join()
    logging.debug('TASK DONE!')

    f.close()
开发者ID:BerndSchuller,项目名称:UP-Tasks,代码行数:31,代码来源:generate_poisson_spiketrains_multithreading_task.py


示例12: GenUrlListThreaded

  def GenUrlListThreaded(self, max_threads=1):
    """Faster way to convert the file_list to url entries in url_list.

    Assumes that the objects will be downloaded from their native host, and
    therefore no prefix is needed.  On pages that have lots of objects, this
    method checks them max_threads at a time until they have all been checked.

    Args:
      max_threads: how many objects to check at once.

    Returns:
      url_list: a reference to the urls pointing to the list of files.

    Raises:
      No exceptions handled here.
      No new exceptions generated here.
    """
    main_thread = threading.currentThread()
    logging.info('fetching %d urls %d at a time', len(self.files), max_threads)
    files = copy.copy(self.files)
    while files:
      ended = (max_threads + 1) - len(threading.enumerate())
      if ended:
        logging.debug('Starting %d HTTP threads', ended)
        for i in range(ended):
          t = threading.Thread(target=self.__GenUrlListThreadedWorker,
                               args=(files,))
          t.start()
          logging.debug('Starting %d of %d HTTP threads', i, ended)
      time.sleep(0.1)
    for t in threading.enumerate():
      if t is not main_thread:
        t.join()
    logging.info('built %d urls', len(self.url_list))
    return self.url_list
开发者ID:shaddi,项目名称:net-lib,代码行数:35,代码来源:http.py


示例13: foo

def foo(iterations):
    for i in range(iterations):
        print threading.currentThread().name,
        print threading.currentThread().ident,
        print threading.activeCount(),
        print threading.enumerate()
        time.sleep(0.2)
开发者ID:jeremiedecock,项目名称:snippets,代码行数:7,代码来源:hello_meth2.py


示例14: start_recording

 def start_recording(self):
     global video
     video = threading.Thread(target=self.screen_capture)
     video.daemon = True
     print(threading.enumerate())
     video.start()
     print(threading.enumerate())
开发者ID:moolya-testing,项目名称:rest-assured,代码行数:7,代码来源:ScreenRecorder.py


示例15: main

def main():
    ok.clear()
    saveImgEvent.set()
    degree = "*"
    unit   = "mm"

    Robot  = ABBProgram()
    RobotQueue.put(Robot)

    if StartEvent.wait(0):
        TakePicture        = threading.Thread(target=takeImage, name="Take Picture")
        TakePicture.daemon = True
        TakePicture.start()

        [Robot.runMain(unit, i) for i in xrange(2, 3)]
        # [Robot.runMain(degree, i) for i in xrange(3, 5)]

        Robot.Home()
        Robot.printDateTime()
        print >> Robot.f, "Program Finished"
    with print_lock:
        raw_input('Close program?')
    Robot.close()
    time.sleep(2)
    # end.wait()
    print threading.enumerate()
开发者ID:PaulDCross,项目名称:TSP_ProgramsData,代码行数:26,代码来源:ABBRobotControlRepeatabilityTestMK3.py


示例16: work

 def work(self):
     """
     Performs the work.
     """
     self._stamp('begin work()')
     logging.info('please be patient, this may take some time...')
     # We attempt analyze each url in the queue.
     # The queue contains initially only the start url.
     # The queue is populated by analyze instances (threads).
     count = 0
     threads_list = []
     finished = False
     while (not finished):
         if (count > self.maxu):
             while (len(threading.enumerate()) > 1): time.sleep(self.dt)
             finished = True
         elif (len(self.urls) > 0): 
             while (len(threading.enumerate()) > self.maxt): 
                 time.sleep(self.dt)
             count += 1
             url = self.urls.pop(0)
             logging.debug('urls=%i(%i,%i) edges=%i vertices=%i threads=%i',
                          len(self.analyzed_urls),
                          len(self.explored),
                          len(self.urls),
                          len(self.edges),
                          len(self.vertices),
                          len(threading.enumerate()))
             self.analyzed_urls.append(url)
             current = _Analyze(url,self)
             threads_list.append(current)
             current.start()
         else: 
             finished = (len(threading.enumerate()) == 1)
     self._stamp('end work()')
开发者ID:djalilchafai,项目名称:w2m,代码行数:35,代码来源:w2m.py


示例17: handle_dataset_form

def handle_dataset_form(dataset_form_):
    keywords = dataset_form_['keywords'].value
    #prefix = dataset_form_['prefix'].value
    
    if 'submit!' == dataset_form_[create_button_txt].value:
        print 'creating!'
        keywords = keywords.split()
        prefix = dataset_form_['prefix'].value
        
        print 'before starting thread:', threading.enumerate()
        t = Thread(target=getThreadForCreateOutput(keywords, prefix, 
                                                   create_outputs), 
                   name=prefix)
        t.start()
        print 'thread started', threading.enumerate()
    elif 'submit!' == dataset_form_[shrink_button_txt].value:
        print 'shrinking!!'
        dataset = dataset_form_['degree_dataset'].value
        new_prefix = dataset_form_['new_prefix'].value
        #new_prefix = dataset + '_' + dataset_form_['threshold'].value
        threshold = int(dataset_form_['threshold'].value)
        
        create_outputs1(dataset, 'data', new_prefix, threshold)
    elif 'submit!' == dataset_form_[merge_button_txt].value:
        print 'merging!!'
        lst = check_checkboxes(dataset_form_)
        merge_prefix = dataset_form_['merge_prefix'].value
        from abstractparser import merge_files
        merge_files('data', lst, merge_prefix)
        
    '''
开发者ID:darrenkuo,项目名称:the_clustering_experiment,代码行数:31,代码来源:main_form.py


示例18: test_multiple_clients_server_disconnect

    def test_multiple_clients_server_disconnect(self):
        """
        Test to check multiple client connect/disconnect scenario.
        """

        numclients = 40

        self.ships = []

        for x in xrange(numclients):
            self.ships.append(AIShip_Network_Harness("Add Me " + str(x), self.__bad_thrust_ship))

            self.assertTrue(self.ships[-1].connect(self.cfg.getint("Server", "port")), "Didn't connect to server.")
        #next

        time.sleep(5)

        self.game.end()

        # server closes all connections
        self.server.disconnectAll()

        time.sleep(10)

        print threading.enumerate()

        self.assertFalse(self.server.isrunning(), "Server still running after disconnect.")

        for x in xrange(numclients):
            self.assertFalse(self.ships[x].isconnected(), "Client still connected to server after disconnect.")

        print threading.enumerate()
        self.assertEqual(len(threading.enumerate()), 1, "More than main thread running.")
开发者ID:demc,项目名称:SpaceBattleArena,代码行数:33,代码来源:ServerTestCases.py


示例19: __exit__

 def __exit__(self, exc_type, exc_val, exc_tb):
     for thread in set(threading.enumerate()) - self.before:
         thread.join(self.timeout)
         if self.check_alive and thread.is_alive():
             raise RuntimeError('Timeout joining thread %r' % thread)
     self.left_behind = sorted(
         set(threading.enumerate()) - self.before, key=lambda t: t.name)
开发者ID:rectalogic,项目名称:mopidy-pandora,代码行数:7,代码来源:conftest.py


示例20: test_block

    def test_block(self):
        b = wspbus.Bus()
        self.log(b)

        def f():
            time.sleep(0.2)
            b.exit()
        def g():
            time.sleep(0.4)
        threading.Thread(target=f).start()
        threading.Thread(target=g).start()
        threads = [t for t in threading.enumerate() if not get_daemon(t)]
        self.assertEqual(len(threads), 3)

        b.block()

        # The block method MUST wait for the EXITING state.
        self.assertEqual(b.state, b.states.EXITING)
        # The block method MUST wait for ALL non-main, non-daemon threads to finish.
        threads = [t for t in threading.enumerate() if not get_daemon(t)]
        self.assertEqual(len(threads), 1)
        # The last message will mention an indeterminable thread name; ignore it
        self.assertEqual(self._log_entries[:-1],
                         ['Bus STOPPING', 'Bus STOPPED',
                          'Bus EXITING', 'Bus EXITED',
                          'Waiting for child threads to terminate...'])
开发者ID:UH-msalem,项目名称:UHCore,代码行数:26,代码来源:test_bus.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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