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