调试sys.path的修改

时间:2015-02-10 13:28:23

标签: python path

有些图书馆似乎修改了我的sys.path,虽然我不想改变。

如何找到改变sys.path

的python代码行

相关

2 个答案:

答案 0 :(得分:7)

导入的第一件事是sitecustomizeusercustomize模块;您可以使用记录所有更改的自定义列表实现替换sys.path

首先,找到放置usercustomizesitecustomize模块的位置; site module可以告诉你在哪里放置第一个:

python -m site --user-site

如果该目录尚不存在,请创建该目录并在其中添加usercustomize.py

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(VerboseSysPath, self).insert(*args)

    def append(self, *args):
        self.croak('append', args)
        return super(VerboseSysPath, self).append(*args)

    def extend(self, *args):
        self.croak('extend', args)
        return super(VerboseSysPath, self).extend(*args)

    def pop(self, *args):
        self.croak('pop', args)
        return super(VerboseSysPath, self).pop(*args)

    def remove(self, *args):
        self.croak('remove', args)
        return super(VerboseSysPath, self).pop(*args)

    def __delitem__(self, *args):
        self.croak('__delitem__', args)
        return super(VerboseSysPath, self).__delitem__(*args)

    def __setitem__(self, *args):
        self.croak('__setitem__', args)
        return super(VerboseSysPath, self).__setitem__(*args)

    def __setslice__(self, *args):
        self.croak('__setslice__', args)
        return super(VerboseSysPath, self).__setslice__(*args)

sys.path = VerboseSysPath(sys.path)

现在这会抱怨改变sys.path列表的所有尝试。

演示,上面放置在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

答案 1 :(得分:1)

使用python -S启动python会导致python无法加载site.py,因此在python首次启动时会保留其默认值。