Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

shell

kill

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.

like image 422
d3pd Avatar asked Mar 15 '15 20:03

d3pd


People also ask

How do you force kill a Python script?

Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.

How do you kill a Python program in terminal?

To stop a python script, just press Ctrl + C. Use the exit() function to terminate Python script execution programmatically. Use the sys. exit() method to stop even multi-threaded programs.


2 Answers

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:~$ 
like image 173

sys.exit(1) will terminate the current program. The parameter is the exit status- anything but 0 indicates abnormal termination.

like image 23
mbatchkarov Avatar answered Sep 20 '22 19:09

mbatchkarov