Python请求异常超时

标签 python exception error-handling timeout

我写了一个像这样的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 block 高于您的except IOError block (或者根据需要将其分解为特定的 requests 错误。

关于Python请求异常超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25257932/

相关文章:

error-handling - 合并两种错误类型的最惯用方式是什么?

error-handling - 如何处理无效 zlib 字节的 Dart 异常

python - 调用子进程

python - 如何在 Python 3 中获取 Unicode 代码点(如从数据库中获取)

python - 使用 Python : Course registration data in JSON 处理数据库

python - 简单LSTM模型: No attr named '_XlaCompile' in name error

c# - try catch 异常

android - SQLite 异常 : Database is locked issue

Java - java.lang.NoClassDefFoundError 何时发生?

java - Spring Boot 调度程序线程随机停止