prattom
prattom

Reputation: 1743

import python module using sys.path.append

I have two python modules which I am trying to import using sys.path.append and sys.path.insert. Following is my code

import sys
sys.path.insert(1, "/home/sam/pythonModules/module1")
sys.path.append("/home/sam/pythonModules/module2")

from lib.module1 import A
from lib.module2 import B

I have following folder structure

/home/sam/pythonModules/module1/lib/module1.py
/home/sam/pythonModules/module2/lib/module2.py

I am able to import lib.module1 but not lib.module2. If I do it like this

import sys
sys.path.insert(1, "/home/sam/pythonModules/module2")
sys.path.append("/home/sam/pythonModules/module1")

from lib.module1 import A
from lib.module2 import B

then I am able to import module2 but not module1.

What can be the reason for the above importing errors?

I tried append instead of insert in following manner but it's still doesn't work

import sys
sys.path.append("/home/sam/pythonModules/module1")
sys.path.append("/home/sam/pythonModules/module2")

from lib.module1 import A
from lib.module2 import B

Always only first module in sys.path.append is successfully imported.

But I make some changes to paths in sys.path.append in following manner then it works. Both the modules are imported successfully

 import sys
 sys.path.append("/home/sam/pythonModules/module1")
 sys.path.append("/home/sam/pythonModules/module2/lib")

 from lib.module1 import A
 from module2 import B

Upvotes: 6

Views: 43757

Answers (2)

Ilija
Ilija

Reputation: 1604

I'm afraid you can't do it that way.

Because of structure:

/home/sam/pythonModules/module1/lib/module1.py
/home/sam/pythonModules/module2/lib/module2.py

You can't put both:

  • /home/sam/pythonModules/module1 and
  • /home/sam/pythonModules/module2

in sys.path and expect that Python will find:

  • module1 in module1/lib and
  • module2 in module2/lib

when you try import like:

from lib.module1 import A
from lib.module2 import B

If you put /home/sam/pythonModules/module1 before /home/sam/pythonModules/module2 in sys.path array, then import lib.MODULE will search for MODULE in /home/sam/pythonModules/module1/lib.

Since there is only module1 and no module2 in it, you get error.

What you can do is to put both

  • /home/sam/pythonModules/module1/lib/ and
  • /home/sam/pythonModules/module2/lib/

in sys.path and expect Python to correctly import them with next lines:

from module1 import A
from module2 import B

Upvotes: 7

ibt23sec5
ibt23sec5

Reputation: 407

Useless to use sys.path.insert, only if you want to prioritize your project before another in PYTHONPATH.

import sys

sys.path.append("/home/sam/pythonModules/module1")
sys.path.append("/home/sam/pythonModules/module2")

from lib.module1 import A 
from lib.module2 import B 

Your projects module1 / module2 should be also structured as valid package, let see official guidelines: http://docs.python-guide.org/en/latest/writing/structure/

Upvotes: 1

Related Questions