Alex Rivera | Logout

Python sys.path modification not working

Asked 2009-06-19T13:14:52.460
11

I'm trying to modify the sys.path in one of my Python files in order to have some specific libraries dirs in the modules search path (it might not be the best way but ...). If I insert several paths in the front of sys.path my script is not taking into account those paths for future imports. If i make a whole new list containing those libraries dirs i need and assign that list to sys.path then those imports are taken into account. Is this the correct behavior? I'm using python 2.5.4. Could it be something from my environment that could lead to such behavior?

Some code snippets: If I do

pathtoInsert1 = " .... "
pathtoInsert2 = " .... "
sys.path.insert(0, pathToInsert1)
sys.path.insert(0, pathToInsert2)

it does not work. It does not take into account the paths.

If I do

pathList = [pathToInsert1, pathToInsert2] 
sys.path = pathList

it works.

Thanks

Edit
Report

2 Answers

3

I just had a similar problem while working in iPython with modules that are distributed over several directories. In that case, to get import to work, one must make sure the module.__path__ of modules with distributed __init__.py includes all directories where one of the module's __init__.py are, as well as making sure the correct directory is in the sys.path list.

For example, I have a module called foo, which contains a module called bar which is spread over several directories:

aerith/foo/bar/__init__.py
aerith/foo/bar/baz/__init__.py
bob/foo/bar/__init__.py
bob/foo/bar/baf/__init__.py
carol/foo/bar/__init__.py
carol/foo/bar/quux/__init__.py

In iPython, I had already imported baz and baf, and wanted to import quux.

from foo.bar import quux

This gave an ImportError, because carol was not in sys.path, but sys.path.append('carol') did not fix the ImportError.

What was required was informing the bar module that one of its __init__.py could be found in 'carol/foo/bar'.

foo.bar.__path__.append('carol/foo/bar')
from foo.bar import quux
answered 2013-03-01T17:46:02.240
2

How are you "inserting" the additional paths?

Modifying the path is done the same way any other list in Python is modified - although it sounds like you're simply clobbering it by re-assigning it.

Example of updating sys.path: http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html

answered 2009-06-19T13:23:05.347

Your Answer