Kill Process with Python

Kill process by name?

Assuming you're on a Unix-like platform (so that ps -A exists),

>>> import subprocess, signal
>>> import os
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()

gives you ps -A's output in the out variable (a string). You can break it down into lines and loop on them...:

>>> for line in out.splitlines():
... if 'iChat' in line:
... pid = int(line.split(None, 1)[0])
... os.kill(pid, signal.SIGKILL)
...

(you could avoid importing signal, and use 9 instead of signal.SIGKILL, but I just don't particularly like that style, so I'd rather used the named constant this way).

Of course you could do much more sophisticated processing on these lines, but this mimics what you're doing in shell.

If what you're after is avoiding ps, that's hard to do across different Unix-like systems (ps is their common API to get a process list, in a sense). But if you have a specific Unix-like system in mind, only (not requiring any cross-platform portability), it may be possible; in particular, on Linux, the /proc pseudo-filesystem is very helpful. But you'll need to clarify your exact requirements before we can help on this latter part.

How do you kill a process in multi-processing with it's PID?

You should probably save the processes in a dict keyed by the process id (pid attribute) for fast lookup. Then you can call terminate on the Process instance:

import multiprocessing as mp

def func():
...

process_dict = {}
for _ in range(10):
process = mp.Process(target=func)
process.start()
process_dict[process.pid] = process
...
# Kill a process given a pid:
# This also removes the key from the dictionary:
process = process_dict.pop(pid)
process.terminate()
...
# Wait for remaining processes to end:
for process in process_dict.values():
process.join()

The assumption is that the pid belongs to one of the processes that you created (otherwise the pop operation will raise a KeyError exception.

The above code assumes you are running under a platform that uses fork to create new processes (such as Linux) and therefore you do not need to place code that creates new processes within a if __name__ == '__main__': block. But you really should tag your question with the platform.



Related Topics



Leave a reply



Submit