Monday, August 8, 2016

How to kill yourself in Python

By Vasudev Ram

Here's a simple Python program that shows how the os.kill function from Python's standard library, along with the os.getpid function and the signal module [1], can be used to terminate the current program - the one it is called from:
'''
Program: test_self_kill.py
A program to show that the os.kill function 
can be used to terminate the current program.
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
https://vasudevram.github.io
http://jugad2.blogspot.com
https://gumroad.com/vasudevram
'''

from __future__ import print_function
import sys, os, signal

print("Python version:", sys.version)
print("This line will be printed.")
os.kill(os.getpid(), signal.SIGTERM)
print("If os.kill works, this line will not be printed.")
Program output when run in Python 2.7:
$ python test_self_kill.py
Python version: 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:40:30) [MSC v.1500
 64 bit (AMD64)]
This line will be printed.
Program output when run in Python 3.6:
$ python test_self_kill.py
Python version: 3.6.0a2 (v3.6.0a2:378893423552, Jun 14 2016, 01:21:40) [MSC v.19
00 64 bit (AMD64)]
This line will be printed.
As you can see, the second call to the print function does not run, because the program terminates itself.
You can read about Unix signals here and here.

- Vasudev Ram - Online Python training and consulting



My Python posts     Subscribe to my blog by email

My ActiveState recipes



No comments: