python - 无需修改第三方代码即可抑制警告

标签 python warnings deprecation-warning

我们使用第三方开源工具,它会生成警告:

DeprecationWarning: The compiler package is deprecated and removed in Python 3.x.

如何在不修改第三方代码的情况下抑制此警告?

我知道如何使用 warnings.filter() 但我无法使用它:我从命令行调用 py.test,因此没有单一源代码我的代码行在创建警告之前执行。

围绕控制台脚本创建包装器不是一个选项。

最佳答案

您可以添加调用 warnings.filter()usercustomizesitecustomize 模块。它将在解释器启动时加载。

参见The Customization Modules :

Python provides two hooks to let you customize it: sitecustomize and usercustomize. To see how it works, you need first to find the location of your user site-packages directory. Start Python and run this code:

>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python2.7/site-packages'

Now you can create a file named usercustomize.py in that directory and put anything you want in it. It will affect every invocation of Python, unless it is started with the -s option to disable the automatic import.

sitecustomize works in the same way, but is typically created by an administrator of the computer in the global site-packages directory, and is imported before usercustomize. See the documentation of the site module for more details.

您可以使用PYTHONUSERBASE environment variable来影响Python的外观。 ,因此您可以在此处将 Python 指向每个项目的 usercustomize.py 文件,前提是您考虑将路径 lib/python/site-packages 添加到基础中:

$ python -m site --user-site
/Users/someuser/Library/Python/2.7/lib/python/site-packages
$ PYTHONUSERBASE=/foo/bar python -m site --user-site
/foo/bar/lib/python/site-packages

在上面的示例中,将 PYTHONUSERBASE 设置为 /foo/bar,Python 将加载 /foo/bar/lib/python/site-packages/usercustomize.py(如果存在)。

在 Python virtualenv 中,使用自定义的 site.py 文件,该文件基于 Python 2.6 之前的 site.py ;此版本省略了 getusersitepackages() 函数。如果文件 lib/pythonX.X/no-global-site-packages.txt 存在,则usercustomize 模块将不会被导入。您必须改用虚拟环境 lib/python/site-packages 目录中的 sitecustomize.py 文件。

关于python - 无需修改第三方代码即可抑制警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24572689/

相关文章:

python - 在可变长度元组列表中查找最常见的元素

python - 如何使用参数别名在 python 中实现弃用

python - 如何使用 z3 Python API 对 bv-redand 进行编码?

python - 处理 ElasticSearch 最 Pythonic 的方法是什么?

python - 当作为参数传递给 range() 时,如何告诉 PyCharm 类实例可以通过 __index__ 方法解释为整数?

ios - 使用 IOS 相机,得到 <wait_fences : failed to receive reply: 10004003>

python - PyBrain 弃用警告

objective-c - 使用@available 抑制 Objective-C 中的弃用警告

python - conda 安装的软件包不适用于 jupyter