python 设置方法超时
2015-04-16 16:56
232 查看
#!/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'
相关文章推荐
- python脚本设置超时机制系统时间的方法
- python脚本设置超时机制系统时间的方法
- python脚本设置系统时间的两种方法
- python运用redis,存储键值,设置超时时间
- PHP file_get_contents设置超时处理方法
- C#访问SqlServer设置链接超时的方法
- linux网络编程之socket(十一):套接字I/O超时设置方法和用select实现超时
- 设置python中TAB键自动补全方法
- Windows API OpenURL无法设置超时时间替换方法
- Python时区设置方法与pytz查询时区教程
- session超时时间设置方法
- Axis1客户端连接超时的设置方法!!!
- SQL查询超时的设置方法
- python socket 超时设置 errno 10054
- python字节序转换+设置套接字超时时间
- python\shell个性化vim设置的方法
- php页面函数设置超时限制的方法
- php页面函数设置超时限制的方法
- Python实现爬虫设置代理IP和伪装成浏览器的方法分享
- Python中为feedparser设置超时时间教程