Max Segal Max Segal - 20 days ago 5
Python Question

Syntax error when killing process tree through Python

I am trying to kill a process tree using this shell command:

kill -TERM -- -3333


so in python I use
subprocess
:

subprocess.call(['kill', '-TERM', '--', '-3333'])


the process is terminated as expected but I get this message:

ERROR: garbage process ID "--".
Usage:
kill pid ... Send SIGTERM to every process listed.
kill signal pid ... Send a signal to every process listed.
kill -s signal pid ... Send a signal to every process listed.
kill -l List all signal names.
kill -L List all signal names in a nice table.
kill -l signal Convert between signal numbers and names.


Why do I get this message and what am I doing wrong?

I am using Python 2.6.5 on Ubuntu 10.04.

Answer

You are passing the kill command an argument it doesn't recognise. You could simply drop the --:

subprocess.call(['kill', '-TERM', '-3333'])

You probably should be passing in the PID without a dash as well, if -- is not supported, neither will a negative PID; at which point you'd be signalling just the single process.

Note that you are not executing this through a shell, while your shell probably has its own kill command implementation, Python instructs the OS to find the first kill binary executable on the path instead. The shell built-in may accept -- but that's not the command you are executing here.

If you must use the shell built-in, then you'll have to set shell=True and pass in a string command line:

subprocess.call('kill -TERM -- -3333', shell=True)

This uses /bin/sh; you can set a different shell to run the command through with the executable argument:

subprocess.call('kill -TERM -- -3333', shell=True, executable='/bin/bash')

Last but not least, you may not need the kill command at all. Python can send signals directly with the os.kill() function:

import os, signal

os.kill(3333, signal.SIGTERM)

and the os.killpg() function can send a signal to a process group:

import os, signal

os.killpg(3333, signal.SIGTERM)
Comments