您的位置:首页 > 编程语言 > Python开发

python代码片段——不断尝试执行cmd

2016-01-06 23:10 656 查看
"""
cmd: 命令
tries: 尝试次数
timeout: 每一次尝试执行时的时间长度
interval: 每一次尝试执行间的时间间隔
"""


@staticmethod
def execute_shell(cmd, tries=1, timeout=10, interval=10):
index = 0
errorContent = ""
while True:
if(index >= tries):
raise Exception(-1,"[{0}] try {1} times still fail:{2}".format(cmd,tries,errorContent))

if timeout:
end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
sub = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE, stdin=subprocess.PIPE,shell=True)

while sub.poll() is None:
time.sleep(0.1)
if timeout:
if end_time <= datetime.datetime.now():
Toolkit.kill_child_processes(sub.pid)
stdout,stderr = sub.communicate()

if sub.returncode == 0:
return sub.returncode,stdout
else:
errorContent = stderr
time.sleep(interval)
index += 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: