So I have a python script that runs a loop in which it calls a program A through subprocess.Popen waits for its output, then saves the output and then calls it again and so on. (This keeps happening for a number of runs I set as an input)
The thing is that I have a timer so that whenever the program A takes more than a particular threshold_time, the script kills the process with process.kill() and moves on to the next iteration.
The problem is that even though everything seems to work fine even for 300 runs, sometimes I get this error:
File "C:\Python27\lib\subprocess.py", line 1002, in terminate
_subprocess.TerminateProcess(self._handle, 1)
WindowsError: [Error 5] Access is denied
and then the script dies.
The referred script part:
timeout = TIME_CONST
for run in runs:
killed = False
start = time.clock()
p = subprocess.Popen("SOME.CMD", cwd=r"some_dir")
# Monitor process. If it hits threshold, kill it and go to the next run
while p.poll() is None:
time.sleep(20)
secs_passed = time.clock() - start
### the following was my initial buggy line ###
#if secs_passed >= timeout:
### corrected line after jedislight's answer ###
#if the time is over the threshold and process is still running, kill it
if secs_passed >= timeout and p.poll is None:
p.kill()
killed = True
break
if killed: continue
Do you have any suggestions what the problem might be?
EDIT: Accepted answer and fixed the code. Thanks @jedislight for your feedback!