sys.path 的调试修改
Debugging modifications of sys.path
有些库似乎修改了我的 sys.path
,尽管我不希望它被更改。
如何找到改变 sys.path
的 python 代码行?
相关
首先导入的东西之一是 sitecustomize
和 usercustomize
模块;您可以将 sys.path
替换为记录所有所做更改的自定义列表实现。
首先,找到放置usercustomize
或sitecustomize
模块的位置; site
module 可以告诉你第一个放在哪里:
python -m site --user-site
如果该目录尚不存在,请创建它并在其中放置一个 usercustomize.py
with:
import sys
class VerboseSysPath(list):
def croak(self, action, args):
frame = sys._getframe(2)
print('sys.path.{}{} from {}:{}'.format(
action, args, frame.f_code.co_filename, frame.f_lineno))
def insert(self, *args):
self.croak('insert', args)
return super().insert(*args)
def append(self, *args):
self.croak('append', args)
return super().append(*args)
def extend(self, *args):
self.croak('extend', args)
return super().extend(*args)
def pop(self, *args):
self.croak('pop', args)
return super().pop(*args)
def remove(self, *args):
self.croak('remove', args)
return super().remove(*args)
def __delitem__(self, *args):
self.croak('__delitem__', args)
return super().__delitem__(*args)
def __setitem__(self, *args):
self.croak('__setitem__', args)
return super().__setitem__(*args)
sys.path = VerboseSysPath(sys.path)
现在这将抱怨所有试图改变 sys.path
列表的尝试。
Demo,上面的内容放在 site-packages/sitecustomize.py
或 `python -m site --user-site`/usercustomize.py
模块中:
$ cat test.py
import sys
sys.path.append('')
$ bin/python test.py
sys.path.append('',) from test.py:3
用 python -S
启动 python 导致 python 不加载 site.py
,因此它的默认值从 python 第一次启动时保留。
有些库似乎修改了我的 sys.path
,尽管我不希望它被更改。
如何找到改变 sys.path
的 python 代码行?
相关
首先导入的东西之一是 sitecustomize
和 usercustomize
模块;您可以将 sys.path
替换为记录所有所做更改的自定义列表实现。
首先,找到放置usercustomize
或sitecustomize
模块的位置; site
module 可以告诉你第一个放在哪里:
python -m site --user-site
如果该目录尚不存在,请创建它并在其中放置一个 usercustomize.py
with:
import sys
class VerboseSysPath(list):
def croak(self, action, args):
frame = sys._getframe(2)
print('sys.path.{}{} from {}:{}'.format(
action, args, frame.f_code.co_filename, frame.f_lineno))
def insert(self, *args):
self.croak('insert', args)
return super().insert(*args)
def append(self, *args):
self.croak('append', args)
return super().append(*args)
def extend(self, *args):
self.croak('extend', args)
return super().extend(*args)
def pop(self, *args):
self.croak('pop', args)
return super().pop(*args)
def remove(self, *args):
self.croak('remove', args)
return super().remove(*args)
def __delitem__(self, *args):
self.croak('__delitem__', args)
return super().__delitem__(*args)
def __setitem__(self, *args):
self.croak('__setitem__', args)
return super().__setitem__(*args)
sys.path = VerboseSysPath(sys.path)
现在这将抱怨所有试图改变 sys.path
列表的尝试。
Demo,上面的内容放在 site-packages/sitecustomize.py
或 `python -m site --user-site`/usercustomize.py
模块中:
$ cat test.py
import sys
sys.path.append('')
$ bin/python test.py
sys.path.append('',) from test.py:3
用 python -S
启动 python 导致 python 不加载 site.py
,因此它的默认值从 python 第一次启动时保留。