0

有些图书馆确实sys.path以我不希望的方式改变了我。

但我找不到它。受影响的 virtualenv 安装了很多库。

我用自己的类替换了 sys.path 来改变修改,但这没有帮助,因为代码似乎改变sys.path如下:

sys.path= [...] + sys.path

如何找到“邪恶”代码行及其堆栈跟踪?

有关的

4

1 回答 1

2

我发现了这样的邪恶代码行。

我在 sitecustomize.py 中更改 sys.globals['sys']:

# sitecustomize.py
import sys

class AttributeIsReadonly(ValueError):
    pass

class MakeModuleAttributesReadonly(object):
    def __init__(self, module, readonly_attributes):
        self.module=module
        self.readonly_attributes=readonly_attributes

    def __setattr__(self, item, value):
        if item in ['module', 'readonly_attributes']:
            return super(MakeModuleAttributesReadonly, self).__setattr__(item, value)
        if item in self.readonly_attributes:
            raise AttributeIsReadonly('Access on attribute %r is readonly' % item)
        return setattr(self.module, item, value)

    def __getattr__(self, item):
        return getattr(self.module, item)

sys.modules['sys']=MakeModuleAttributesReadonly(sys, ['path'])

#import sys
#sys.path=sys.path # this will raise the above AttributeIsReadonly

它引发了AttributeIsReadonly,我看到了代码行和堆栈跟踪。

于 2015-10-19T10:47:28.243 回答