Python请求异常超时

MLSC

我写了这样的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错误,如果你想要的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章