yangcctv 发表于 2018-8-5 14:15:45

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

  python通过subprocess模块调用系统命令。实际使用中,有一次是命令进入了交互模式,结果web端直接卡死了。调用时设置一个超时时间,时间用完后自动断开。这样就避免了系统因为调用命令而僵死的问题。
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()
  
            exitcode = p.poll() if p.poll() else 0
  
            return res, exitcode, res
  
      seconds_passed = time.time() - t_beginning
  
      if timeout and seconds_passed > timeout:
  
            p.terminate()
  
            out, exitcode, err = '', 128, '执行系统命令超时'
  
            return out, exitcode, err
  
      time.sleep(0.1)
  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()
  exitcode = p.poll() if p.poll() else 0
  return res, exitcode, res
  seconds_passed = time.time() - t_beginning
  if timeout and seconds_passed > timeout:
  p.terminate()
  out, exitcode, err = '', 128, '执行系统命令超时'
  return out, exitcode, err
  time.sleep(0.1)
  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()
  exitcode = p.poll() if p.poll() else 0
  return res, exitcode, res
  seconds_passed = time.time() - t_beginning
  if timeout and seconds_passed > timeout:
  p.terminate()
  out, exitcode, err = '', 128, '执行系统命令超时'
  return out, exitcode, err
  time.sleep(0.1)
页: [1]
查看完整版本: Python调用系统命令设置超时时间