之前发过一个类似的http://www.redicecn.com/html/Python/20120906/434.html,但是仅支持Windows平台,在Linux下命令超时后进程杀不死。
下面的方法能够同时支持Windows和Linux平台:
import os import platform import subprocess import signal import time class TimeoutError(Exception): pass def command(cmd, timeout=60): """Run command and return the output cmd - the command to run timeout - max seconds to wait for """ 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__': try: result = command('ping www.site-digger.com', timeout=10) except TimeoutError: print 'Run command timeout.' else: print result
呵呵,谢谢
VaTG790i.最好的<a href=http://www.kyfei.com>网站推广软件</a>,
非常好
....................
;ui;普i;uighur;ui;ui;个
在unix网络编程中看到了关于TCP/IP的一些内容,我感觉还是写的不够。正在下载中,一定
下载地址呢