Find the exact PID first, then send a graceful signal before using SIGKILL.
1. Find the Python process
pgrep -af 'python|python3' # or ps -eo pid,ppid,pgid,stat,etime,cmd | grep -E '[p]ython'
Look at the command line, user, and script path so you don’t kill the wrong process. Useful columns:
S = sleeping/interruptibleD = uninterruptible sleep, often blocked on I/OZ = zombiePGID = process group2. Try to terminate it gracefully
kill -TERM <PID>
Wait a few seconds and check:
sleep 5 ps -p <PID> -o pid,ppid,pgid,stat,etime,cmd
If it’s an interactive/foreground Python process, Ctrl-C or:
kill -INT <PID>
may also work.
3. If it is still running, force-kill it
sudo kill -KILL <PID> # same as sudo kill -9 <PID>
Verify it’s gone:
ps -p <PID>
If you want to match by script name
Be careful with pkill -f; it can match unrelated processes.
pkill -TERM -f '/path/to/your_script.py' sleep 5 pkill -KILL -f '/path/to/your_script.py'
Better to confirm with pgrep -af '/path/to/your_script.py' first.
If the Python process has children
Inspect the tree:
pstree -p <PID>
Kill children explicitly if needed:
kill -TERM <PID> <child_pid1> <child_pid2>
Only use process-group killing if you’re sure the group contains only that job:
ps -o pid,pgid,cmd -p <PID> kill -TERM -<PGID>
If it’s managed by systemd
systemctl status <service-name> sudo systemctl stop <service-name>
If necessary:
sudo systemctl kill -s SIGKILL <service-name>
Special cases
D: it’s blocked in uninterruptible I/O. SIGKILL will remain pending until the kernel I/O completes. Investigate disk/NFS/storage issues.Z: it’s already dead but not reaped. Kill or restart its parent.sudo, but verify the PID first.Useful diagnostic before killing:
py-spy dump --pid <PID> # or sudo strace -p <PID>
General rule: use kill -TERM first, wait, then use kill -KILL only if it won’t exit.