简体   繁体   English

如何跳过子进程超时

[英]How to skip subprocess timeout

I'm reading off a file and looping the websites into a subprocess call which uses a script to connect to it and outputs it to terminal. 我正在读取文件,并将网站循环到一个子过程调用中,该子过程使用脚本连接到该文件并将其输出到终端。 Some websites do not connect and I need to skip them. 有些网站无法连接,我需要跳过它们。

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

Without the timeout, it just hangs for too long 没有超时,它会挂太久

I tried 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

but it shows an error: 但显示错误:

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

On some sites it calls the exception and goes to the next site, but on some of them it doesnt even go to the exception and outputs the error shown 在某些站点上,它调用异常并转到下一个站点,但是在某些站点上,它甚至没有转到异常并输出所显示的错误

You should be able to catch the TimeoutExpired execption and ignore it 您应该能够捕获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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM