0
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

So, this code launches another Python script for a number of times, each python script contains an infinite while loop, so, I am trying to create a function that kills whatever number of processes are generated by that above function. I tried stuff like

x.terminate()

But that just does not work, I think that should kill all the sub-processes, but it does not do that, I think it might be killing the last launched process or something along those lines, but my question is, how can I kill whatever number of processes launched by my first function?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • You're overwriting the `x` variable each time through the loop, so it just contains the last subprocess you started. Put them in a list, and then kill all of them in a loop. – Barmar Jan 31 '15 at 14:00
  • I don't think it is possible to assign every single process it's own unique variable, for a possibly unique number of processes every time.. can you provide an example for how I can do that? – user3907837 Jan 31 '15 at 14:39
  • 1
    I didn't say unique variables, I said to make a list. – Barmar Jan 31 '15 at 14:39

1 Answers1

0

Put all the subprocesses in a list instead of overwriting the x variable

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()
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • That function to kill all the subprocesses do not work, sadly. and it does not output any errors, but I can still see the processes running. – user3907837 Jan 31 '15 at 15:53
  • I got your example to work using some heavy modifications to the closing sections, thank you for pointing me in the right direction! – user3907837 Jan 31 '15 at 20:23
  • @user3907837: `p.kill()` kills the shell. It does not kill the python script and its descendants (if any). – jfs Feb 01 '15 at 03:19