Nathan Miller
Nathan Miller

Reputation: 55

Kill not responding exe file in Python script

I'm running a kind of touchy .exe file in Python to receive a couple of data measurements. The file should open, take the measurement, then close. The issue is sometimes it crashes and I need to be able to take these measurements every 10 minutes over a long period of time.

What I need is a 'check' to see if the .exe is not responding and if it's not, then to have it kill the process. Or to just kill the whole script after every measurement taken. The issue is that the script gets stuck when it tries to run the .exe file that's not responding.

Here's the script:

FNULL = open(os.devnull, 'a')   

filename = "current_pressure.log"

command = '"*SRH#\r"'

args = "httpget -r -o " + filename  + " -C 2 -S " + command + IP 

subprocess.call(args, stdout=FNULL, stderr=FNULL, shell=False)

Basically, need something like:

"if httpget.exe not responding, then kill process" 

OR

"kill above script if running after longer than 20 seconds"

Upvotes: 1

Views: 1713

Answers (2)

Nitin Sutar
Nitin Sutar

Reputation: 11

Generally, when a program hangs while working on windows we try to go to Task Manager and end the process of that particular program. When this approach fails, we experiment with some third party softwares to terminate it. However, there is even another better way for terminating such hanged programs automatically

http://www.problogbooster.com/2010/01/automatically-kills-non-responding.html

Upvotes: 1

tdelaney
tdelaney

Reputation: 77337

Use a timer to kill the process if its gone on too long. Here I've got two timers for a graceful and hard termination but you can just do the kill if you want.

import threading

FNULL = open(os.devnull, 'a')   
filename = "current_pressure.log"
command = '"*SRH#\r"'
args = "httpget -r -o " + filename  + " -C 2 -S " + command + IP 

proc = subprocess.Popen(args, stdout=FNULL, stderr=FNULL, shell=False)

nice = threading.Timer(20, proc.terminate)
nice.start()
mean = threading.Timer(22, proc.kill)
mean.start()
proc.wait()
nice.cancel()
mean.cancel()

Upvotes: 1

Related Questions