How to terminate a python subprocess launched with shell=True
Let's immediately stop a subprocess with shell=True using Popen from subprocess and invoke terminate():
This sends a friendly SIGTERM. If polite asking didn't work, send a signal they can't ignore, use proc.kill() to send a SIGKILL.
Group Therapy: Managing Process Groups
Running a subprocess that breeds like rabbits? A.k.a. spawns loads of child processes? Killing Papa process may not make the kids stop. To clean up the entire family group, we use os.setsid() in a preexec_fn during Popen. It's like starting a fitness boot camp that ensures the whole family works out:
Dodge and Weave: Avoiding shell=True
To assert your dominance over subprocess termination and dodge shell=True, execute commands straight up! Pass your command as a sequence (not the dance one, sorry) to Popen:
Remember, cmd.split() is your BFF for going from shell=True to shell=False.
The Hulk: Handling Stubborn Processes
Dealing with a moody process that gives you the silent treatment after a SIGTERM? Go psychology on them and use psutil:
Crisis Management: Handling Timeout Scenarios
Got a deadline to meet? Use TimeoutExpired to forcibly terminate a subprocess if proc.wait(timeout) doesn't return in time:
But I'm on Windows...
For Windows users, terminating subprocesses and their child processes requires adjustments. Never change, Windows, never change. Bring in the taskkill command to settle the score:
For Real Though: Subprocess Kill Techniques
The Secret Technique: exec Prefix
In the cases where shell=True is just unavoidable, prefixing the command with exec helps ensure that p.kill() goes after the actual Bash process:
Fine Tuning with psutil
For process management precision, the psutil library is like the Rolex of Python tools. Here's how you can use it to lay down the law on stubborn subprocesses:
Mind the Pipes
When putting exec to work, remember to consider the impact on pipes and redirections. This could make your command read like gibberish. The fix? Careful structuring. Comment monologues not included.
Was this article helpful?