gpt4 book ai didi

python - 杀死另一个线程产生的进程

转载 作者:行者123 更新时间:2023-11-30 23:10:23 25 4
gpt4 key购买 nike

我有一个Python进程,它从一个单独的线程生成另一个进程,例如

class MyClass(unittest.TestCase):

def setup(self):
def spawn_proc():
subprocess.call("test_process")

thread = threading.Thread(target=spawn_proc, args=(), daemon=True)
thread.start()

def cleanup(self):
# @@@ kill test_process

因此调用 MyClass.setup() 意味着 test_process 将在第二个线程中生成。

我想要的是一种从第一个线程中终止 test_process 的方法。我尝试在 spawn_proc() 中保存对进程的引用,但在第一个线程中这是无法访问的,因为 spawn_proc() 在第二个线程中执行。

执行此操作的最佳方法是什么?或者这种方法从一开始就是错误的?

的作用是再次调用subprocess从操作系统中查找PID,然后进一步调用kill,但我不确定是否有更好的方法。

最佳答案

问题是 subprocess.call() 不返回任何线程句柄。它是一个同步方法(仅当被调用的程序终止时才返回)。

而是使用subprocess.Popen():

def setup(self):
self.proc = subprocess.Popen("test_process")


def cleanup(self):
self.proc.kill()

您不仅获得了句柄,还完全避免了线程模块。

有关 Popen 的更多详细信息(例如如何与进程通信): https://docs.python.org/2/library/subprocess.html#popen-constructor

关于python - 杀死另一个线程产生的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30712822/

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