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
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
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!