1

I have a python script that runs another python program and then gathers results from the logs. The only problem is that I want it to run a limited number of seconds. So I want to kill the process after say, 1 minute.

How can I do this?

I'm running an external program with the command os.system("./test.py")

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • maybe worth a check: http://stackoverflow.com/questions/4033578/how-to-limit-programs-execution-time-when-using-subprocess – alexcepoi May 17 '13 at 19:50

3 Answers3

2

you need more control over your child process than os.system allows for. subprocess, especially Popen and Popen objects give you enough control for managing child processes. For a timer, see again the section in the standard library

Thomas Fenzl
  • 4,342
  • 1
  • 17
  • 25
2

Check out the psutil module. It provides a cross-platform interface to retrieving information on all running processes, and allows you to kill processes also. (It can do more, but that's all you should need!)

Here's the basic idea of how you could use it:

import os
import psutil
import time


os.system('./test.py')
# Find the PID for './test.py'. 
# psutil has helper methods to make finding the PID easy.
pid = <process id of ./test.py>  

time.sleep(60)
p = psutil.Process(pid)
p.kill()
Tom Offermann
  • 1,391
  • 12
  • 12
1
#!/usr/bin/env python
import time, os, subprocess
process = subprocess.Popen(
    ['yes'], stdout=open(os.devnull,'w'))
time.sleep(60)
process.terminate()
Hal Canary
  • 2,154
  • 17
  • 17