简体   繁体   中英

Package and module import in python

Here is my folder structure:

|sound
|-__init__.py
|-model
  |-__init__.py
  |-module1.py
  |-module2.py
|-simulation
  |-sim.py

The file module1.py contains the code:

class Module1:
    def __init__(self,mod):
        self.mod = mod

The file module2.py contains the code:

class Module2:
    def __init__(self,mods=None):
        if mods is None:
            mods = []
        self.mods = mods
    def append(self.mod):
        mods.append(mod)

Finally the file sim.py contains the code:

import sound

sound_1 = sound.module2.Module2()

When I execute sim.py I get a ModuleNotFoundError: No module named 'sound'

I've tried pretty much everything such as from sound.model import module2 etc. but I believe the problem comes from python not finding the sound package.

I've read several tutos, docs and threads, and I don't understand what I'm doing wrong.

That's because python is looking for a module sound inside simulation folder. When you try to execute python file this way:

python sim.py

You should instead create run.py in the same folder as sound

sound/
  model/
    ...
  simulation/
run.py

with the following content:

from sound.simulator import sim

And run it with python run.py , that way python sets workdir to folder containing sound


Also in sim.py you should import the module as following:

import sound.model.module1
sound.model.module1.Module1()

Or like this:

from sound.model import module1
module1.Module1()

Explanation when module is being imported, python looks for a folder sound or a file sound.py in directories listed in sys.path , the first one being '' (current working directory).

When running python files, for some reason python sets current workdir to the folder containing the file, even if it is run like python sound/simulation/sim.py

To prevent this behaviour, we have to create run.py in the directory which we want to be workdir (ie directory containing sound), so when python sees import sound , it searchs the correct directory

The simple FIX:

  • Move sim.py one folder up into sound
  • Try import module2
  • sound_1 = module2.Module2()

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