1

Problems importing python modules from other directories?

My project has been getting bigger and the correct modules are failing to import properly. Result is the program stops running at the first line. Here is what my directory map currently looks like:

PROTOTYPE
- Sound_editor (folder)
- - openant (cloned library from Github)
- - - __init__.py
- - - (a bunch of files and folders from the library)
- - - demo.py

- - __init__.py
- - editor.py
- - reader.py
- - streamer.py
- - main2.py

- main1.py

The problem that I am getting repeatedly, in many different forms is this:
streamer.py

from editor import A_class

main1.py

import Sound_editor.streamer

When I run main1.py, it first imports streamer file. Then the streamer file attempts and fails to import the editor file. error

ModuleNotFoundError: No module named 'editor'

I don't know what else to do. I've tried:

  1. So many things from this guide: https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html
  2. variations of dotting my way to the right path: import PROTOTYPE.Sound_editor.editor
  3. using from: from Sound_editor import editor as well as from Sound_editor.editor import A_class
  4. I've studied this answer: Importing files from different folder. I'm not sure what he means by structuring directories as a package. I have already added init.py files. (They are empty..)

What else should I try. Do you experts see any obvious errors?

Submitted July 19th 2021 by Admin

Answers
0

you can add to the Python path at runtime:

some_file.py

import sys

insert at 1, 0 is the script path (or '' in REPL)

sys.path.insert(1, '/path/to/application/app/folder')

import file

Admin | 6 days ago


0

from editor import A_class is an absolute import. Python will only look in directories that appear in sys.path for a module named editor. When you run main1.py, Sound_editor is found because it's in the same directory as main1.py; editor is not.

What you want is a relative import, so that editor is found in whatever package streamer itself is found in:

from .editor import A_class

Admin | 6 days ago



Relevant Questions