当前位置: 首页>>代码示例>>Python>>正文


Python threading.enumerate函数代码示例

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


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


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