0

I've got the following file structure: enter image description here

I'm trying to initialize some objects in main.py that belong to modules in the Listener, Parser and Configurations folders.

I understand I can't just write import listener since it's not in the same path. What simple ways are there for the imports to work without adding the paths to the PYTHONPATH env variable? Is there a way to make it work on any machine "out of the box" without the need to add the paths to PYTHONPATH or any solution like that? Preferably something with a relative path like in C++?

matanc1
  • 6,525
  • 6
  • 37
  • 57

1 Answers1

0

Possible duplicate: Importing from a relative path in Python

In short, you need to programmatically define PYTHONPATH in main.py, something like:

import sys, os
sys.path.append(os.path.dirname(__file__))

This implicitly adds current directory to PYTHONPATH. Rest of the part is straightforward

Create __init__.py file in each of the directories. After that, each of the modules can be imported as from Listener import ... or from Misc import ... etc.

The approach works 'out of box' without redefining any environmental variable.

Community
  • 1
  • 1
Sudeep Juvekar
  • 4,898
  • 3
  • 29
  • 35
  • This answer doesn't answer how to import from two level above directory. the ... is only for one leve. Any idea? THx – ephraim Dec 16 '18 at 09:28