Python 官方文档:入门教程 => 点击学习
#!/usr/bin/python #-*-coding:utf-8-*- import os,time,signal,platfORM,subprocess class TimeoutError(Exception): pas
#!/usr/bin/python
#-*-coding:utf-8-*-
import os,time,signal,platfORM,subprocess
class TimeoutError(Exception):
pass
def run_command(cmd, timeout=60):
is_linux = platform.system() == 'Linux'
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid if is_linux else None)
t_beginning = time.time()
seconds_passed = 0
while True:
if p.poll() is not None:
break
seconds_passed = time.time() - t_beginning
if timeout and seconds_passed > timeout:
if is_linux:
os.killpg(p.pid, signal.SIGTERM)
else:
p.terminate()
raise TimeoutError(cmd, timeout)
time.sleep(0.1)
return p.stdout.read()
if __name__ == '__main__':
cmd = 'ping www.Google.com
timeout = 10
try:
result = run_command(cmd, timeout)
except TimeoutError:
print 'excute command=<%s> timeout after %i' %(cmd,timeout)
else:
print = 'other error'
--结束END--
本文标题: python 设置方法超时
本文链接: https://lsjlt.com/news/186649.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0