Python请求异常超时



我写了一个这样的python脚本:

#!/usr/bin/python
import sys
import requests
if len(sys.argv) != 2:
        print "Usage: python %s <IP-LIST>" % (sys.argv[0])
        sys.exit();
InputFile = sys.argv[1]
try:
    File = open(InputFile)
    for ip in File:
        IP = ip.rstrip()
        out = requests.get("http://" + IP, timeout=5)
        out.status_code
except (KeyboardInterrupt, SystemExit):
    print "nKeyboardInterruption with Ctrl+c signal"
except IOError as e:
    print "The file "%s" does not exist!" % (sys.argv[1])

当url没有任何响应时,显示以下输出:

The file "list.txt" does not exist!

为什么?

requests使用子类IOError的异常,您正在捕获并假设未找到文件。如果你使用Python 3,你可以捕获更具体的FileNotFoundError。在这里,您应该将except requests.RequestException放在except IOError之上(或者如果您愿意,将其分解为特定的requests错误)。

最新更新