删除Python UserWarning

kag*_*gat 42 python

我刚刚完成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)
Run Code Online (Sandbox Code Playgroud)

有没有办法摆脱这个?

Wal*_*han 78

您可以更改~/.python-eggs为群组/所有人无法写入.我认为这有效:

chmod g-wx,o-wx ~/.python-eggs
Run Code Online (Sandbox Code Playgroud)


jh3*_*314 21

您可以使用以下命令禁止警告-W ignore:

python -W ignore yourscript.py
Run Code Online (Sandbox Code Playgroud)

如果你想在脚本中压制警告(引用文档):

如果您使用的代码会引发警告(例如已弃用的函数),但不希望看到警告,则可以使用catch_warnings上下文管理器来禁止警告:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
Run Code Online (Sandbox Code Playgroud)

在上下文管理器中,所有警告都将被忽略.这允许您使用已知弃用的代码,而不必查看警告,同时不抑制可能不知道其使用已弃用代码的其他代码的警告.注意:这只能在单线程应用程序中得到保证.如果两个或多个线程同时使用catch_warnings上下文管理器,则行为未定义.

如果您只想忽略警告,可以使用filterwarnings:

import warnings
warnings.filterwarnings("ignore")
Run Code Online (Sandbox Code Playgroud)