當前位置: 首頁>>代碼示例>>Python>>正文


Python threading.enumerate方法代碼示例

本文整理匯總了Python中threading.enumerate方法的典型用法代碼示例。如果您正苦於以下問題:Python threading.enumerate方法的具體用法?Python threading.enumerate怎麽用?Python threading.enumerate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在threading的用法示例。


在下文中一共展示了threading.enumerate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: start

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def start(self):
        if self.finalized:
            self.bus.log('Already deamonized.')

        # forking has issues with threads:
        # http://www.opengroup.org/onlinepubs/000095399/functions/fork.html
        # "The general problem with making fork() work in a multi-threaded
        #  world is what to do with all of the threads..."
        # So we check for active threads:
        if threading.activeCount() != 1:
            self.bus.log('There are %r active threads. '
                         'Daemonizing now may cause strange failures.' %
                         threading.enumerate(), level=30)

        self.daemonize(self.stdin, self.stdout, self.stderr, self.bus.log)

        self.finalized = True 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:19,代碼來源:plugins.py

示例2: test_builtin_channels

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def test_builtin_channels(bus, listener):
    """Test that built-in channels trigger corresponding listeners."""
    expected = []

    for channel in bus.listeners:
        for index, priority in enumerate([100, 50, 0, 51]):
            bus.subscribe(
                channel,
                listener.get_listener(channel, index),
                priority,
            )

    for channel in bus.listeners:
        bus.publish(channel)
        expected.extend([msg % (i, channel, None) for i in (2, 1, 3, 0)])
        bus.publish(channel, arg=79347)
        expected.extend([msg % (i, channel, 79347) for i in (2, 1, 3, 0)])

    assert listener.responses == expected 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:21,代碼來源:test_bus.py

示例3: test_custom_channels

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def test_custom_channels(bus, listener):
    """Test that custom pub-sub channels work as built-in ones."""
    expected = []

    custom_listeners = ('hugh', 'louis', 'dewey')
    for channel in custom_listeners:
        for index, priority in enumerate([None, 10, 60, 40]):
            bus.subscribe(
                channel,
                listener.get_listener(channel, index),
                priority,
            )

    for channel in custom_listeners:
        bus.publish(channel, 'ah so')
        expected.extend(msg % (i, channel, 'ah so') for i in (1, 3, 0, 2))
        bus.publish(channel)
        expected.extend(msg % (i, channel, None) for i in (1, 3, 0, 2))

    assert listener.responses == expected 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:22,代碼來源:test_bus.py

示例4: run

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def run(self):
        window_name = "Olympe Streaming Example"
        cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
        main_thread = next(
            filter(lambda t: t.name == "MainThread", threading.enumerate())
        )
        while main_thread.is_alive():
            with self.flush_queue_lock:
                try:
                    yuv_frame = self.frame_queue.get(timeout=0.01)
                except queue.Empty:
                    continue
                try:
                    self.show_yuv_frame(window_name, yuv_frame)
                except Exception:
                    # We have to continue popping frame from the queue even if
                    # we fail to show one frame
                    traceback.print_exc()
                finally:
                    # Don't forget to unref the yuv frame. We don't want to
                    # starve the video buffer pool
                    yuv_frame.unref()
        cv2.destroyWindow(window_name) 
開發者ID:Parrot-Developers,項目名稱:olympe,代碼行數:25,代碼來源:streaming.py

示例5: main

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def main():
    password = getpass()
    start_time = datetime.now()

    hostnames = [
        'arista1.twb-tech.com',
        'arista2.twb-tech.com',
        'arista3.twb-tech.com',
        'arista4.twb-tech.com',
    ]

    print()
    print(">>>>>")
    for host in hostnames:
        net_device = create_device_dict(host, password)
        my_thread = threading.Thread(target=scp_file, args=(net_device,))
        my_thread.start()

    main_thread = threading.currentThread()
    for some_thread in threading.enumerate():
        if some_thread != main_thread:
            some_thread.join()
    print(">>>>>")

    print("\nElapsed time: " + str(datetime.now() - start_time)) 
開發者ID:ktbyers,項目名稱:python_course,代碼行數:27,代碼來源:exercise2_with_threads.py

示例6: main

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def main():
    '''
    Use threads and Netmiko to connect to each of the devices in the database. Execute
    'show version' on each device. Record the amount of time required to do this.
    '''
    start_time = datetime.now()
    devices = NetworkDevice.objects.all()

    for a_device in devices:
        my_thread = threading.Thread(target=show_version, args=(a_device,))
        my_thread.start()

    main_thread = threading.currentThread()
    for some_thread in threading.enumerate():
        if some_thread != main_thread:
            print(some_thread)
            some_thread.join()

    print("\nElapsed time: " + str(datetime.now() - start_time)) 
開發者ID:ktbyers,項目名稱:python_course,代碼行數:21,代碼來源:ex6_threads_show_ver.py

示例7: _threads

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def _threads(self):
        threads = list(threading.enumerate())
        d = {
            "num_threads": len(threads),
            "threads": [
                {"name": t.name, "ident": t.ident, "daemon": t.daemon} for t in threads
            ],
        }
        # Only available in Python 3.7+
        if hasattr(asyncio, "all_tasks"):
            tasks = asyncio.all_tasks()
            d.update(
                {
                    "num_tasks": len(tasks),
                    "tasks": [_cleaner_task_str(t) for t in tasks],
                }
            )
        return d 
開發者ID:simonw,項目名稱:datasette,代碼行數:20,代碼來源:app.py

示例8: worker_int

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def worker_int(worker):
    worker.log.info("worker received INT or QUIT signal")

    # get traceback info
    import threading
    import sys
    import traceback

    id2name = {th.ident: th.name for th in threading.enumerate()}
    code = []
    for threadId, stack in list(sys._current_frames().items()):
        code.append("\n# Thread: %s(%d)" % (id2name.get(threadId, ""), threadId))
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                code.append("  %s" % (line.strip()))
    worker.log.debug("\n".join(code)) 
開發者ID:archesproject,項目名稱:arches,代碼行數:19,代碼來源:gunicorn_config.py

示例9: on_timeout

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def on_timeout():
    logger.debug("cli timeout ")
    # Timeout should have been handled by the orchestrator, if the cli timeout
    # has been reached, something is probably wrong : dump threads.
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])
        print()

    if orchestrator is None:
        logger.debug("cli timeout with no orchestrator ?")
        return
    global timeout_stopped
    timeout_stopped = True

    orchestrator.stop_agents(20)
    orchestrator.stop()
    _results("TIMEOUT")
    sys.exit(0) 
開發者ID:Orange-OpenSource,項目名稱:pyDcop,代碼行數:21,代碼來源:orchestrator.py

示例10: on_timeout

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def on_timeout():
    logger.debug("cli timeout ")
    # Timeout should have been handled by the orchestrator, if the cli timeout
    # has been reached, something is probably wrong : dump threads.
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])
        print()

    if orchestrator is None:
        logger.debug("cli timeout with no orchestrator ?")
        return
    global timeout_stopped
    timeout_stopped = True
    # Stopping agents can be rather long, we need a big timeout !
    logger.debug("stop agent on cli timeout ")
    orchestrator.stop_agents(20)
    logger.debug("stop orchestrator on cli timeout ")
    orchestrator.stop()
    _results("TIMEOUT")
    # sys.exit(0)
    os._exit(2) 
開發者ID:Orange-OpenSource,項目名稱:pyDcop,代碼行數:24,代碼來源:solve.py

示例11: on_timeout

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def on_timeout():
    if orchestrator is None:
        return
    # Timeout should have been handled by the orchestrator, if the cli timeout
    # has been reached, something is probably wrong : dump threads.
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])
        print()
    if orchestrator is None:
        logger.debug("cli timeout with no orchestrator ?")
        return
    global timeout_stopped
    timeout_stopped = True

    # Stopping agents can be rather long, we need a big timeout !
    orchestrator.stop_agents(20)
    orchestrator.stop()
    _results("TIMEOUT")
    sys.exit(0) 
開發者ID:Orange-OpenSource,項目名稱:pyDcop,代碼行數:22,代碼來源:run.py

示例12: on_timeout

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def on_timeout():
    global result, output_file
    global start_t
    duration = time.time() - start_t

    print("TIMEOUT when distributing")
    logger.info("cli timeout when distributing")
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])

    result["status"] =  "TIMEOUT"
    result["inputs"]["duration"] = duration

    if output_file is not None:
        with open(output_file, encoding="utf-8", mode="w") as fo:
            fo.write(yaml.dump(result))
    print(yaml.dump(result))

    #os._exit(0)
    sys.exit(0) 
開發者ID:Orange-OpenSource,項目名稱:pyDcop,代碼行數:23,代碼來源:distribute.py

示例13: thread_stacktraces

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def thread_stacktraces():
  """
  Provides a dump of the stacktrace information for all active threads.

  :returns: **dict** that maps thread names to their stacktrace
  """

  stacktraces = {}

  for thread in threading.enumerate():
    frame = sys._current_frames().get(thread.ident, None)

    if frame:
      stacktraces[thread.name] = ''.join(traceback.format_stack(frame))
    else:
      stacktraces[thread.name] = 'No traceback available'

  return stacktraces 
開發者ID:torproject,項目名稱:stem,代碼行數:20,代碼來源:output.py

示例14: test_enumerate_after_join

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def test_enumerate_after_join(self):
        # Try hard to trigger #1703448: a thread is still returned in
        # threading.enumerate() after it has been join()ed.
        enum = threading.enumerate
        old_interval = sys.getcheckinterval()
        try:
            for i in xrange(1, 100):
                # Try a couple times at each thread-switching interval
                # to get more interleavings.
                sys.setcheckinterval(i // 5)
                t = threading.Thread(target=lambda: None)
                t.start()
                t.join()
                l = enum()
                self.assertNotIn(t, l,
                    "#1703448 triggered after %d trials: %s" % (i, l))
        finally:
            sys.setcheckinterval(old_interval) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:20,代碼來源:test_threading.py

示例15: test_highlevel

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import enumerate [as 別名]
def test_highlevel():
    """Test highlevel mailbox API"""
    for lazy in [False, True]:
        print(f"Lazy mode: {lazy}")

        mb = strax.Mailbox(lazy=lazy)
        mb.add_sender(iter(list(range(10))))

        def test_reader(source):
            test_reader.got = r = []
            for s in source:
                r.append(s)

        mb.add_reader(test_reader)
        mb.start()
        time.sleep(SHORT_TIMEOUT)
        assert hasattr(test_reader, 'got')
        assert test_reader.got == list(range(10))
        mb.cleanup()
        assert len(threading.enumerate()) == 1, "Not all threads died" 
開發者ID:AxFoundation,項目名稱:strax,代碼行數:22,代碼來源:test_mailbox.py


注:本文中的threading.enumerate方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。