AndrewOnFire
AndrewOnFire

Reputation: 59

How to kill an executable that was launched from within a Python script

I am writing a Python script that requires the use of an executable that occasionally gets stuck in an infinite loop. When stuck in this loop, the executable spits out the same line of text to standard out. This I intend to catch and once I do, kill the executable. When I run this script manually I can just use CTRLC.

What is the correct way to programmatically kill off the executable from within the Python script? I am using Python 2.7, yet I am also curious as to the 3.x solution. I am using an os.system() call.

Upvotes: 2

Views: 80

Answers (1)

Stefan Collier
Stefan Collier

Reputation: 4682

You could attempt to catch the SIGINT close all your subprocess instances then do a system exit.

#!/usr/bin/env python
import signal
import sys
import subprocess

p = subprocess.Popen(...)

# define how to handle CTRL+C
def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    p.kill()
    sys.exit(0)

# Tell it to handle CTRL+C
signal.signal(signal.SIGINT, signal_handler)

Upvotes: 1

Related Questions