gpt4 book ai didi

python - 如何立即停止正在运行单元测试的 python 子进程?终止并杀死不起作用

转载 作者:行者123 更新时间:2023-12-01 06:16:02 25 4
gpt4 key购买 nike

我有一个 Tkinter GUI 运行两个线程,GUI 的主要线程和工作线程。工作线程使用以下代码创建子进程:

myProcess = subprocess.Popen(['python', '-u', 'runTests.py'],  
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)

文件 runTests.py 进行一些设置,然后使用以下命令运行单元测试文件:

execfile('myUnitTests.py')

文件 myUnitTests.py 有几个单元测试,其中一些需要五分钟以上的时间才能运行。在 GUI 中,我单击一个按钮来停止运行测试。这反过来又使工作线程发送信号来停止子进程:

myProcess.terminate()

终止命令不会立即停止进程,而是等到当前单元测试运行完毕后才终止进程?我尝试过使用 os.kill,但得到与 Terminate() 相同的结果。

知道如何使我的程序响应更快,以便它立即终止子进程吗?

最佳答案

Python 文档 [ http://docs.python.org/library/signal.html ] 说:

  • Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the “atomic” instructions of the Python interpreter. This means that signals arriving during long calculations implemented purely in C (such as regular expression matches on large bodies of text) may be delayed for an arbitrary amount of time.

因此,如果您的五分钟单元测试正在执行“纯粹用 C 实现的长计算”,并且您的单元测试工具安装了 SIGTERM 的处理程序,那么这就是您的问题。如果是这样,请尝试使用 myProcess.kill 而不是 myProcess.terminate (或者,如果您还没有 2.6,则使用 myProcess.send_signal(9) )。 SIGKILL 无法从用户空间捕获,并且应该立即生效。

警告:任何应该在单元测试框架之外运行的清理操作都不会被执行。

关于python - 如何立即停止正在运行单元测试的 python 子进程?终止并杀死不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3302910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com