d3pd d3pd - 6 months ago 34
Bash Question

How can I get a Python program to kill itself using a command run through the module sys?

I want to see how a Python program could kill itself by issuing a command using the module

sys
. How could I get it to kill itself using a command of the following form?:

os.system(killCommand)





EDIT: emphasising for clarity

So, just to be clear, I want to have a string that gets run in the shell that kills the Python program.

Answer

You can use sys.exit() to exit the program normally.

Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is an integer, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure).


The system command to kill the interpreter itself depends on the shell used; if your shell is bash or zsh, you can use:

a@host:~$ python
Python 2.7.8 (default, Oct 20 2014, 15:05:19) 
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system('kill $PPID')
Terminated
a@host:~$

Though your actual results may vary. To be safer, you need to provide the process ID yourself:

>>> os.system('kill %d' % os.getpid())

If you want to just a get signal sent to your process, you can also use os.kill() with the process id of your process; the process id of currently running process is available from os.getpid():

a@host:~$  python
Python 2.7.8 (default, Oct 20 2014, 15:05:19) 
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.kill(os.getpid(), 9)
[1]    27248 killed     python
a@host:~$