【问题标题】:How to skip subprocess timeout如何跳过子进程超时
【发布时间】:2017-03-11 15:27:03
【问题描述】:

我正在读取一个文件并将网站循环到一个子进程调用中,该子进程调用使用脚本连接到它并将其输出到终端。有些网站无法连接,我需要跳过它们。

cmd = subprocess.check_output([os.path.dirname(sys.argv[0])+ SCRIPT],  stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=1)

没有超时,就是挂了太久

我试过了,除了

try
    cmd = subprocess.check_output([os.path.dirname(sys.argv[0])+ SCRIPT],  stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=1)

except subprocess.CalledProcessError:
    print(e)
    #pass

但它显示错误:

Traceback (most recent call last):
  File "/usr/lib/python3.5/subprocess.py", line 695, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/usr/lib/python3.5/subprocess.py", line 1072, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "/usr/lib/python3.5/subprocess.py", line 1716, in _communicate
    self._check_timeout(endtime, orig_timeout)
  File "/usr/lib/python3.5/subprocess.py", line 1098, in _check_timeout
    raise TimeoutExpired(self.args, orig_timeout)
subprocess.TimeoutExpired: Command '['./SCRIPT timed out after 1 seconds

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./find_prime.py", line 22, in <module>
    stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=1)
  File "/usr/lib/python3.5/subprocess.py", line 626, in check_output
    **kwargs).stdout
  File "/usr/lib/python3.5/subprocess.py", line 700, in run
    stderr=stderr)
subprocess.TimeoutExpired: Command '['./SCRIPT']' timed out after 1 seconds

在某些站点上它调用异常并转到下一个站点,但在其中一些站点上它甚至不转到异常并输出显示的错误

【问题讨论】:

    标签: python timeout subprocess


    【解决方案1】:

    您应该能够捕获 TimeoutExpired 执行并忽略它

    try:
        cmd = subprocess.check_output([os.path.dirname(sys.argv[0])+ SCRIPT], stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=1)
    except subprocess.CalledProcessError e:
        print(e)
    except subprocess.TimeoutExpired:
        pass
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 2011-04-13
      • 2011-04-22
      相关资源
      最近更新 更多