Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 977
prattom Avatar asked Jul 26 '26 18:07

prattom


1 Answers

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
like image 103
Ilija Avatar answered Jul 29 '26 06:07

Ilija



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!