0

So here is my tree of files:

project/
   moduleToImport.py
   folder1/
      willImport.py

I can't import moduleToImport.py in my willImport.py file. I execute it like this:

usr@machine:~/home$ /test/anotherFolder/project/folder1/willImport.py --args "a" "b" "c"

So when I try this solution:

from .. import moduleToImport

The willImport.py file tries to import from ../home not /project, so he can't find the moduleToImport.py.

Another solution that I found out there is:

import sys
sys.path.append("/path/to/dir")
from app import object

But it doesn't work if I use a relative path (which is going to be necessary), like:

sys.path.append("..")
from .. import moduleToImport

Because it will have the same problem as before: he imports from ../home.

The main problem is, I can't use an absolute path because it will change.

Any ideas?

Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Did you try adding empty `__init__.py` files in each folder? – Ralf Dec 20 '18 at 12:47
  • add `__init__.py` file in each folder `project` and `folder1` . then from there trying to import as `from project import moduleToImport` – sahasrara62 Dec 20 '18 at 13:00

1 Answers1

0

Folders

project/
  moduleToImport.py
  folder1/
    willImport.py

willImport.py

import os
import sys

runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))

from moduleToImport import func

func()

moduleToImport.py

def func():
    print("Success")

OUTPUT:

Success
Ali.Turkkan
  • 266
  • 2
  • 11