Perl转Python开发者咨询:requests.get()异常捕获简化方案
解决pylint对
except Exception:的宽泛提示问题 针对你的场景,有两种简便方案可以不用逐一列出requests的9种异常:
方案1:捕获requests.exceptions.RequestException
requests库所有请求相关的异常都继承自requests.exceptions.RequestException,直接捕获这个父类就能覆盖所有请求层面的异常,同时不会误捕KeyboardInterrupt这类系统级中断异常,既满足需求又符合pylint的规范:
import requests import sys try: response = requests.get("https://example.com") response.raise_for_status() # 可选:捕获HTTP错误状态码对应的异常 except requests.exceptions.RequestException as e: print(f"请求出错: {e}") sys.exit(1)
方案2:添加pylint忽略注释
如果你确实想保留except Exception:(比如要捕获所有可能的异常后直接退出),可以在该行添加pylint的忽略注释,跳过broad-except警告:
import requests import sys try: response = requests.get("https://example.com") except Exception as e: # pylint: disable=broad-except print(f"程序出错: {e}") sys.exit(1)
这种方式适合你只需要快速终止程序的场景,但注意它会捕获除SystemExit外的几乎所有异常,可能隐藏一些非请求类的问题。
补充说明
pylint标记except Exception:是因为该写法会覆盖绝大多数非系统级异常,可能导致未预期的问题被隐藏。而捕获RequestException是更精准的做法,既能覆盖所有requests请求异常,又不会过度捕获。
内容的提问来源于stack exchange,提问作者Tom Legrady
相关产品推荐
相关产品推荐

