【问题标题】:Python requests exceptions timeoutPython 请求异常超时
【发布时间】:2014-10-05 03:31:01
【问题描述】:

我写了一个这样的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!

为什么?

【问题讨论】:

    标签: python exception error-handling timeout


    【解决方案1】:

    requests 使用子类IOError 的异常,您正在捕获并假设未找到文件。如果您使用的是 Python 3,则可以捕获更具体的 FileNotFoundError。在这里,您应该在except IOError上方 放置一个except requests.RequestException 块(或者如果需要,将其分解为特定的requests 错误。

    【讨论】:

    • 我明白了,谢谢......但是你能解释更多关于“或者如果你愿意的话把它分解成特定的请求错误”如果你有例子我会很感激...... :)
    • 我的意思是requests 中大约有六个例外。基异常类是RequestException,这样可以捕获所有异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多