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.
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.
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.
You can use sys.exit()
to exit the program normally.
Exit the interpreter by raising
SystemExit(status)
. If the status is omitted orNone
, 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:~$
sys.exit(1)
will terminate the current program. The parameter is the exit status- anything but 0 indicates abnormal termination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With