Search code examples
pythonsubprocesspopenkill

subprocess.Popen is creating two processes instead of one


I am creating a subprocess using this line of code:

p = subprocess.Popen(["doesItemExist.exe", id], shell=False)

and when I run the script while I have the Task Manager open, I can see that it creates two processes and not one. The issue is that when I go to kill it, it kills one (using p.kill()), but not the other. I've tried looking online but the only examples I find are about shell=True and their solutions don't work for me. I've confirmed that that line only gets called once.

What can I do? Popen is only giving me back the one pid so I don't understand how to get the other so I can kill both.


Solution

  • I ended up being able to deal with this issue by creating a clean up function which just uses the following:

    subprocess.run(["taskkill", "/IM", "doesItemExist.exe", "/F"], shell=True)

    This will kill any leftover tasks. If anyone uses this, be careful that your exe has a unique name to prevent you from killing anything you don't mean to. If you want to hide the output/errors, just set the stdout and stderr to subprocess.PIPE.

    Also, if there is no process to kill it will report that as an error.