检查python当前正在执行什么线程 [英] Check what thread is currently doing in python

查看:158
本文介绍了检查python当前正在执行什么线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,可以问一个线程当前正在做什么吗?一些代码可能看起来像这样:

In python, is it possible to ask a thread what its currently doing? Some code might look like this:

import threading
import time
import random


def foo():
    a = 'spam'


def bar():
    if random.random() < 0.01:      # go into an infinite loop 1% of the time
        while True:
            x = 42

def run(heartbeat):
    while True:
        foo()
        bar()
        heartbeat.set()

heartbeat = threading.Event()
t = threading.Thread(target=run, args=(heartbeat, ))
t.start()

while True:
    time.sleep(1)
    if heartbeat.is_set():
        heartbeat.clear()
    else:
        print('Thread appears stuck at the following location: ')
        print(get_thread_position(t))

我正在尝试执行此操作以监视线程是否挂起.心跳事件检查它们是否处于活动状态并正常进行.但是,如果他们挂在某个地方,我希望能够找到哪里.那就是我发明了get_thread_position()的地方,我想向其当前执行的函数返回类似追溯的信息.这样,我就可以使用该信息来弄清楚它如何陷入某个无限循环中.

I'm looking to do this to monitor threads to see if they're hanging. The heartbeat event checks whether they're active and progressing normally. However, if they hang somewhere, I'd like to be able to find out where. That's where I've invented get_thread_position() which I would like to return something like a traceback to the function its currently executing. That way, I can use that information to figure out how its getting stuck in some infinite loop.

推荐答案

您可以使用sys._current_frames()来为当前正在运行的每个线程选择一个顶级帧列表,然后在其中查找您的线程,然后检查其帧,像:

You can use sys._current_frames() to pick up a list of top frames for each currently running thread, then find your thread in it and then inspect its frame, something like:

import sys

def get_thread_position(thread):
    frame = sys._current_frames().get(thread.ident, None)
    if frame:
        return frame.f_code.co_filename, frame.f_code.co_name, frame.f_code.co_firstlineno

这将返回一个元组,其中包含该线程中当前正在执行的函数的文件名,函数名称和行号.当然,您也可以选择其他框架信息.如果找不到该线程(即同时死亡),它将不会返回任何内容(None)

This will return you a tuple with the filename, function name and line number of the function currently executing in that thread. Of course, you can pick up other frame info as well. If the thread cannot be found (i.e. died in the meantime) it will not return anything (None)

这篇关于检查python当前正在执行什么线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆