我们使用第三方开源工具,它会生成警告:
DeprecationWarning: The compiler package is deprecated and removed in Python 3.x.
如何在不修改第三方代码的情况下抑制此警告?
我知道如何使用 warnings.filter()
但我无法使用它:我从命令行调用 py.test
,因此没有单一源代码我的代码行在创建警告之前执行。
围绕控制台脚本创建包装器不是一个选项。
最佳答案
您可以添加调用 warnings.filter()
的 usercustomize
或 sitecustomize
模块。它将在解释器启动时加载。
Python provides two hooks to let you customize it:
sitecustomize
andusercustomize
. 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 beforeusercustomize
. See the documentation of thesite
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/