当前位置: 首页>>代码示例>>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;未经允许,请勿转载。