1

I am using python command

import commands
tmp = "my command" #any command like ls
status, output = commands.getstatusoutput(tmp)

It works perfectly. Now i have few commands which may take more than 5 seconds or stuck forever. I want to kill such commands after 5 second. Any pointers.

Saurabh Shrivastava
  • 1,394
  • 4
  • 21
  • 50
  • 1
    You can use a subprocess module: https://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout – Rafał Aug 15 '18 at 12:48

2 Answers2

1

You can use the subprocess module (commands is deprecated).

import shlex, subprocess, time
command = "command"
args = shlex.split(command)
p = subprocess.Popen(args)

start_time = time.time()
while time.time() - start_time < timeout:
    time.sleep(0.1)
    if p.poll() is not None:
        break

if p.returncode is not None:
    p.kill()
Scaatis
  • 137
  • 2
  • 10
0

I figured out the easiest solution:

from easyprocess import EasyProcess
tmp = "my command" #any command like ls
s = EasyProcess(tmp).call(timeout=5)
print "return_code: ",s.return_code
print "output: ", s.stdout
Saurabh Shrivastava
  • 1,394
  • 4
  • 21
  • 50