321312 发表于 2015-6-19 11:04:37

Python调用系统命令设置超时时间

from subprocess import Popen, PIPE
import time


def sys_command_outstatuserr(cmd, timeout=120):
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
    t_beginning = time.time()
    seconds_passed = 0
    while True:
      if p.poll() is not None:
            res = p.communicate()
            return res, res, p.poll()
      seconds_passed = time.time() - t_beginning
      if timeout and seconds_passed > timeout:
            p.terminate()
            out, err, exitcode = '', '执行系统命令超时', 128
            return out, err, exitcode
      time.sleep(0.1)


页: [1]
查看完整版本: Python调用系统命令设置超时时间