简体   繁体   中英

python __import__() imports from 2 different directories when same module exists in 2 locations

I have a python application , which has directory structure like this.

-pythonapp
   -mainpython.py   
   -module1
      -submodule1
          -file1.py
          -file2.py

      -submodule2
           -file3.py
           -file3.py

      -submodule3
           -file1.py
           -file2.py
           -file5.py
           -file6.py
           -file7.py

when I try to import the python utilities(from mainpython.py) under submodule3 , I get the initial 2 files from submodule1.(please note that submodule1 and 3 have 2 different files with the same name). However the same import works fine when there is no conflict ie it correctly imports file 5,6,7 from submodule3.

Here is the code :

name=os.path.splitext(os.path.split("module1\submodule3\file1.py")[1])[0] --> file1.py name here is passed dynamically. 

module = __import__(name) 

//Here is name is like "file1" it works(but with the above said issue, though, when passes the name of the file dynamically), but if I pass complete package as "module1.submodule1.file1" it fails with an ImportError saying that "no module with name file1"

Now the question is how do we tell the interpreter to use only the ones under "module1.submodule3.file2"? I am using python

This is really urgent one and I have run out of all the tries. Hope some experienced python developers can solve this for me?

Try to create packages out of your directory by having a having an empty __init__.py file in each and whenever you want to reference a particular module from a package using

from submodule import mymodule

Syntax. Creating packages are a good way to separate the modules into different namespaces. And name your modules according to its functionality, don't have them as file1, file2 etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM