0

I have a number of Python files in a parent folder called 'API' and I'm trying to link them together:

API/auth/module1.py
API/subfolder/prgm.py

From the parent to the child folders, I have an init.py file containing paths or program names to call, however when I go to execute '/subfolder/prgm.py' that has a call to import 'module1.py', I get the following error at execution:

machine01% ./prgm.py
Traceback (most recent call last):
  File "./prgm.py", line 2, in <module>
    from API.auth.module1 import authFunction
ModuleNotFoundError: No module named 'API'

This is the import statement I have in 'prgm.py':

from API.auth import module1

This question is a bit different from previous ones because I am trying to get a python script that is already in one sub-folder to access a module in another subfolder but under the same parent 'API' folder. Previous questions involved the python script being based in the parent folder and calling modules located in sub-folders.

xorLogic
  • 399
  • 4
  • 14
  • Possible duplicate of [Import a file from a subdirectory?](https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory) – KeZ Jan 25 '19 at 17:01
  • `API` is neither on your `PYTHONPATH`, nor on the default search path, nor in the current working directory. – chepner Jan 25 '19 at 17:01
  • @chepner: Eww, PYTHONPATH looks disgusting since I'm working with my own modules! – xorLogic Jan 25 '19 at 17:04
  • @KeZ, very similar, but not quite a duplicate because in that instance, their code calling the module in a subdirectory is in the parent directory, not a separate subdirectory. – xorLogic Jan 25 '19 at 17:11

2 Answers2

1

try """from . auth import module1""" may be?

sanji
  • 11
  • 3
  • 1
    Mmm, I get the following: `ModuleNotFoundError: No module named '__main__.auth'; '__main__' is not a package`. I'm not sure what this `__main__` is for, but other examples only show that an `__init__.py` file is necessary. – xorLogic Jan 25 '19 at 17:12
1

If you really need to run API/subfolder/prgm.py which in turn import API/auth/module1.py

In prgm.py you could add a parent directory (which is 'API') to sys.path like this:

import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)

And now you could import anything from inside of 'API':

from auth import module1
Litvin
  • 330
  • 1
  • 9