0

Some library does change my sys.path in a way that I don't want it to.

But I can't find it. The affected virtualenv has a lot of libraries installed.

I replaced sys.path with a own class which alters the modifications, but this does not help, since the code seems to alter sys.path like this:

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

How can I find the "evil" code line and its stack trace?

Related

Community
  • 1
  • 1
guettli
  • 25,042
  • 81
  • 346
  • 663

1 Answers1

2

I found the evil code line like this.

I alter sys.globals['sys'] in sitecustomize.py:

# 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

It raises AttributeIsReadonly and I see the code line and the stack trace.

guettli
  • 25,042
  • 81
  • 346
  • 663
  • Why didn't you just add this as an alternative answer to the existing question? – jonrsharpe Oct 19 '15 at 10:51
  • 1
    Since in the current question sys.path does not get **modified**. It is a different question. It's related but not the same. – guettli Oct 19 '15 at 10:58
  • But surely having both answers in the same place would be more helpful for other users? Modification and replacement of the list are *technically* different, but you're solving the same underlying problem. Note that you could also have approached this by implementing `__add__` in `VerboseSysPath`. – jonrsharpe Oct 19 '15 at 11:02
  • @jonrsharpe `__add__` won't work if the modification gets done like this `sys.path = [...] + sys.path`. But thank you for the feedback, I will update the question. – guettli Oct 19 '15 at 11:58
  • Yes, you'd need `__radd__` etc. as well. I still don't see this as different enough to justify a separate question. – jonrsharpe Oct 19 '15 at 11:59
  • 1
    @jonrsharpe: having differently worded questions can be very helpful when searching for a problem. – Ethan Furman Feb 01 '16 at 19:28
  • @EthanFurman mainly if they're linked as duped to one canonical source of relevant information, though... – jonrsharpe Feb 01 '16 at 19:29