Skip to content Skip to sidebar Skip to footer

Debugging Modifications Of Sys.path

Some library seems to modify my sys.path, although I don't want ìt to be changed. How can I find the python code line which alters sys.path? Related Where does sys.path get repla

Solution 1:

One of the first things imported is the sitecustomize and usercustomize modules; you could replace sys.path with a custom list implementation that records all changes being made.

First, find where to place a usercustomize or sitecustomize module; the site module can tell you where to place the first:

python -m site --user-site

If that directory doesn't exist yet, create it and in it put a usercustomize.py with:

import sys

classVerboseSysPath(list):
    defcroak(self, action, args):
        frame = sys._getframe(2)
        print('sys.path.{}{} from {}:{}'.format(
            action, args, frame.f_code.co_filename, frame.f_lineno))

    definsert(self, *args):
        self.croak('insert', args)
        returnsuper(VerboseSysPath, self).insert(*args)
    
    defappend(self, *args):
        self.croak('append', args)
        returnsuper(VerboseSysPath, self).append(*args)

    defextend(self, *args):
        self.croak('extend', args)
        returnsuper(VerboseSysPath, self).extend(*args)

    defpop(self, *args):
        self.croak('pop', args)
        returnsuper(VerboseSysPath, self).pop(*args)

    defremove(self, *args):
        self.croak('remove', args)
        returnsuper(VerboseSysPath, self).remove(*args)

    def__delitem__(self, *args):
        self.croak('__delitem__', args)
        returnsuper(VerboseSysPath, self).__delitem__(*args)

    def__setitem__(self, *args):
        self.croak('__setitem__', args)
        returnsuper(VerboseSysPath, self).__setitem__(*args)

    def__setslice__(self, *args):
        self.croak('__setslice__', args)
        returnsuper(VerboseSysPath, self).__setslice__(*args)

sys.path = VerboseSysPath(sys.path)

This now will complain about all attempts at altering the sys.path list.

Demo, with the above placed in either the site-packages/sitecustomize.py or `python -m site --user-site`/usercustomize.py modules:

$ cat test.py 
import sys

sys.path.append('')
$ bin/python test.py 
sys.path.append('',) from test.py:3

Solution 2:

Starting python with python -S causes python not to load site.py, and so its default value is preserved from when python first starts up.

Post a Comment for "Debugging Modifications Of Sys.path"