Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何终止子进程中打开的所有子进程_Python_Python 3.x_Subprocess_Python 3.4 - Fatal编程技术网

Python 如何终止子进程中打开的所有子进程

Python 如何终止子进程中打开的所有子进程,python,python-3.x,subprocess,python-3.4,Python,Python 3.x,Subprocess,Python 3.4,因此,这段代码多次启动另一个Python脚本,每个Python脚本都包含一个无限while循环,因此,我试图创建一个函数,该函数将杀死上述函数生成的任何数量的进程。 我试过像这样的东西 def example_function(self): number = self.lineEdit_4.text() #Takes input from GUI start = "python3 /path/to/launched/script.py "+variable1+"

因此,这段代码多次启动另一个Python脚本,每个Python脚本都包含一个无限while循环,因此,我试图创建一个函数,该函数将杀死上述函数生成的任何数量的进程。 我试过像这样的东西

def example_function(self):
        number = self.lineEdit_4.text() #Takes input from GUI
        start = "python3 /path/to/launched/script.py "+variable1+" "+variable2+" "+variable3 #Bash command to execute python script with args.
        for i in range(0,number):
            x = subprocess.Popen(start,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)#Launch another script as a subprocess

但这根本不起作用,我认为这应该杀死所有的子进程,但它没有这样做,我认为它可能会杀死最后启动的进程或类似的东西,但我的问题是,如何终止由第一个函数启动的任意数量的进程?

将所有子进程放在一个列表中,而不是覆盖
x
变量

x.terminate()

每次循环都会覆盖
x
变量,因此它只包含您启动的最后一个子流程。把它们放在一个列表中,然后在一个循环中杀死所有的进程。我认为不可能为每个进程分配它自己的唯一变量,因为每次都可能有唯一数量的进程。。你能举个例子说明我是如何做到这一点的吗?我没有说唯一变量,我说的是制作一个列表。遗憾的是,杀死所有子进程的函数不起作用。它不会输出任何错误,但我仍然可以看到进程在运行。我通过对结束部分的一些重大修改获得了您的示例,感谢您为我指明了正确的方向@user3907837:
p.kill()
杀死外壳。它不会杀死python脚本及其子体(如果有的话)。
def example_function(self):
    number = self.lineEdit_4.text() #Takes input from GUI
    start = "python3 /path/to/launched/script.py "+variable1+" "+variable2+" "+variable3 #Bash command to execute python script with args.
    procs = []
    for i in range(0,number):
        x = subprocess.Popen(start,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)#Launch another script as a subprocess
        procs.append(x)
    # Do stuff
    ...
    # Now kill all the subprocesses
    for p in procs:
        p.kill()