0

what is the best way to add timeout for command if unable to complete in 5 seconds.

from subprocess import check_output
try:
    check_output("dh")
except Notexecuted:
    print"command not successful executed"

Version=python2.7

preethy tulpi
  • 415
  • 1
  • 5
  • 15
  • 1
    Possible duplicate of [Timeout on a function call](https://stackoverflow.com/questions/492519/timeout-on-a-function-call) – Chris Feb 13 '18 at 14:27

1 Answers1

0

In python 2.7 we don't have a directly implemented timeout function with subprocess. Instead I suggest subprocess32 package.

from subprocess32 import Popen, PIPE

cmd = "<your command>"
response = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = response.communicate(timeout=5)

( In python 3.x we have this timeout param with default subprocess)

PS: Refer the documentation.

POSIX users (Linux, BSD, etc.) are strongly encouraged to install and use the much more recent subprocess32 module instead of the version included with python 2.7. It is a drop in replacement with better behavior in many situations.

Hope this Help!

Chamath
  • 2,016
  • 2
  • 21
  • 30