删除 Python 用户警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17626694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove Python UserWarning
提问by kagat-kagat
I just finished installing my MySQLdb
package for Python 2.6, and now when I import it using import MySQLdb
, a user warning appear will appear
我刚刚MySQLdb
为 Python 2.6安装了我的包,现在当我使用 导入它时import MySQLdb
,会出现一个用户警告
/usr/lib/python2.6/site-packages/setuptools-0.8-py2.6.egg/pkg_resources.py:1054:
UserWarning: /home/sgpromot/.python-eggs is writable by group/others and vulnerable
to attack when used with get_resource_filename. Consider a more secure location
(set with .set_extraction_path or the PYTHON_EGG_CACHE environment variable).
warnings.warn(msg, UserWarning)
Is there a way how to get rid of this?
有没有办法摆脱这个?
采纳答案by Waleed Khan
You can change ~/.python-eggs
to not be writeable by group/everyone. I think this works:
您可以更改~/.python-eggs
为不可由组/所有人写入。我认为这有效:
chmod g-wx,o-wx ~/.python-eggs
回答by jh314
You can suppress warnings using the -W ignore
:
您可以使用以下命令抑制警告-W ignore
:
python -W ignore yourscript.py
If you want to supress warnings in your script (quote from docs):
If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:
如果您使用的代码知道会引发警告,例如已弃用的函数,但不想看到警告,则可以使用 catch_warnings 上下文管理器抑制警告:
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.
而在上下文管理器中,所有警告都将被忽略。这允许您使用已知已弃用的代码而不必查看警告,同时不会抑制其他可能不知道其使用已弃用代码的代码的警告。注意:这只能在单线程应用程序中得到保证。如果两个或多个线程同时使用 catch_warnings 上下文管理器,则行为未定义。
If you just want to flat out ignore warnings, you can use filterwarnings
:
如果您只想消除忽略警告,可以使用filterwarnings
:
import warnings
warnings.filterwarnings("ignore")