import datetime
import subprocess
import time
def execute_command(cmdstring, timeout=None):
if timeout:
end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
sub = subprocess.Popen(cmdstring, stdin=subprocess.PIPE, bufsize=4096, shell=True)
while sub.poll() is None:
time.sleep(0.1)
if timeout:
if end_time <= datetime.datetime.now():
sub.kill()
return "TIME_OUT"
return str(sub.returncode)
参考网络实现。加上kill
如果需要输出结果,则应修改为:
def execute_command(cmdstring, timeout=None):
if timeout:
end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
sub = subprocess.Popen(cmdstring, stdin=subprocess.PIPE, bufsize=4096, shell=True)
while True:
if sub.poll() is not None:
break
time.sleep(0.1)
if timeout:
if end_time <= datetime.datetime.now():
sub.kill()
return "TIME_OUT"
return str(sub.stdout.read())