Python 3.7 中忽略 CryptographyDeprecationWarning 和 warnings 模块使用问题总结

学习笔记作者:admin日期:2025-07-31点击:8

摘要:在 Python 3.7 中,由于 cryptography 库不再支持该版本,会触发 CryptographyDeprecationWarning。可以通过升级 Python、忽略警告或降级 cryptography 来解决。此外,如果遇到 import warnings 报错,可能是文件名冲突导致,应避免使用 warnings.py 作为文件名,并使用虚拟环境隔离环境。

Python 3.7 中忽略 CryptographyDeprecationWarning 和 warnings 模块使用问题总结

1. 为什么会出现 CryptographyDeprecationWarning?

      当你使用 Python 3.7 并导入 cryptography.exceptions 或使用依赖于 cryptography 的库时,会触发 CryptographyDeprecationWarning

      原因:Python 3.7 已经停止官方支持,cryptography 不再提供支持。

2. 如何忽略 CryptographyDeprecationWarning?

方法 1:升级 Python 到 3.8 或更高版本(推荐)

  • Python 3.7 的官方支持已于 2023 年结束。
  • 升级到 Python 3.8、3.9、3.10、3.11 或 3.12 后,这个警告将不再出现。
  • 下载地址:https://www.python.org/downloads/

方法 2:忽略特定警告(临时解决方案)

import warnings
from cryptography.utils import CryptographyDeprecationWarning

warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning)

方法 3:通过命令行忽略警告

python -W ignore::CryptographyDeprecationWarning your_script.py

方法 4:降级 cryptography 版本(不推荐)

pip install "cryptography==3.4.8"

      注意:3.4.8 是最后一个支持 Python 3.7 的版本。

3. 如何忽略所有警告?

方法 1:在代码中忽略所有警告

import warnings
warnings.filterwarnings("ignore")

方法 2:通过命令行参数忽略所有警告

python -W ignore your_script.py

方法 3:忽略特定类别警告

import warnings
from cryptography.utils import CryptographyDeprecationWarning

warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)

4. import warnings 报错的可能原因

原因 1:文件名冲突

      如果你的文件名为 warnings.py,Python 会尝试导入你自己的文件,而不是标准库的 warnings 模块,这会导致错误。

解决方法:

  • 不要使用 warnings.py 作为文件名。
  • 删除当前目录中的 warnings.pywarnings.pyc 文件。
  • 使用虚拟环境隔离环境。

5. 使用虚拟环境(推荐)

python3.7 -m venv venv
source venv/bin/activate  # Linux/macOS
# 或
venv\Scripts\activate   # Windows

pip install cryptography

6. 总结

方法 描述 推荐程度
升级 Python 到 3.8+ 最根本、最安全的解决办法 ⭐⭐⭐⭐⭐
忽略警告 适合临时使用或调试 ⭐⭐⭐
降级 cryptography 仅限于无法升级 Python 的情况

7. 注意事项

  • 使用 warnings.filterwarnings("ignore") 会全局生效,影响整个程序。
  • 开发阶段建议保留警告信息,以便及时发现问题。
  • 生产环境中可以考虑忽略非关键警告,但应保留重要警告。

上一篇      下一篇