如何跳过子进程超时

How to skip subprocess timeout

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

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

没有超时,只是挂得太久了

我试过 try and except

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

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

您应该能够捕获 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