使用Wing IDE调试多线程Python

1 投票
3 回答
765 浏览
提问于 2025-04-15 13:38

我正在用Wing IDE调试一个多线程的Python程序。

当我按下暂停按钮时,它只会暂停一个线程。我试了十次,每次都是暂停同一个线程,在我这个例子里叫做“ThreadTimer Thread”,而其他线程还是继续运行。我想暂停这些其他线程,这样我才能逐步调试它们。我该怎么做呢?

相关问题:

3 个回答

0

我在创建线程的时候就给它们起个名字。

下面是一个线程的例子:

import threading
from threading import Thread

#...
client_address = '192.168.0.2'
#...

thread1 = Thread(target=thread_for_receiving_data,
                         args=(connection, q, rdots),
                         name='Connection with '+client_address,
                         daemon=True)
thread1.start()

这样你就可以在线程内部随时访问这个名字了。

print(threading.currentThread())
sys.stdout.flush() #this is essential to print before the thread is completed

你还可以列出所有具有特定名字的线程。

for at in threading.enumerate():
    if at.getName().split(' ')[0] == 'Connection':
        print('\t'+at.getName())

对进程也可以做类似的事情。

下面是一个进程的例子:

import multiprocessing


process1 = multiprocessing.Process(target=function,
                         name='ListenerProcess',
                         args=(queue, connections, known_clients, readouts),
                         daemon=True)
process1.start()

对于进程来说,情况更好,因为你可以在外部通过名字来结束一个特定的进程。

for child in multiprocessing.active_children():
    if child.name == 'ListenerProcess':
        print('Terminating:', child, 'PID:', child.pid)
        child.terminate()
        child.join()
1

根据文档的说明,所有正在运行Python代码的线程默认情况下都会被停止(也就是说,除非你特别去做一些其他的设置)。你看到的那些没有被停止的线程,是在运行非Python代码吗(比如输入输出操作,这样会有其他问题),还是说你在做一些不同的事情,比如在没有按照文档描述的方式进行安装和调整,只是暂停了一部分线程呢……?

1

我不太确定在Wing IDE中是否可以进行多线程调试。

不过,你可能会对Winpdb感兴趣,它是可以进行这种调试的工具。

撰写回答