0

I'm using python 3 and My folder structure is as below

Main_Folder
> Export
> >exportmanager.py

> Examples
>  >test.py

exportmanager.py file has a class ExportManager which I need to import in test.py. so far I have tried

from Export.exportmanager import ExportManager
from Main_Folder.Export import exportmanager.py then from exportmanager.py import ExportManager

and some other. But I keep getting no module found.

Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19

2 Answers2

0

The only quick, dirty solution that came to my mind is having this structure:

.
├── Examples
│   ├── __init__.py
│   └── test.py
├── Main_Folder
│   ├── Export
│   │   └── exportmanager.py
│   └── __init__.py
├── __init__.py

And suppose your exportmanager.py looks like this:

def fun():
    print("This is from Export Manager!")

And then you import this in your test.py using:

import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from Main_Folder.Export import exportmanager


exportmanager.fun()

I tried using relative imports, other "simplest" solutions, all of them gave the same error "ImportError: attempted relative import with no known parent package". So if you're looking for a dirty workaround, this might be it. As to why there are a few init.py files, which are basically empty in this case, I encourage you to read about it more (i.e. here)

Have fun.

Mr. 0xCa7
  • 100
  • 7
0

Suppose your you exportmanager.py looks like this:

def fun():
    print("This is from Export Manager!")

You can write this code in your test.py:

from pathlib import Path
from sys import path
path.append(str(Path(__file__).parents[1] /Path('Main/Export')))

import exportmanger

exportmanger.fun()

I try to using answer by Przemysław Samsel, but it makes a ModuleNotFoundError!

  • That's another take I guess, I don't really get what's the division "/" doing there. What my code does it's just appending parent directory to Python's path. Then, if you've created all those __init__.py files as I've pointed out, Python should have not problem finding the exportmanager. Anyway, let's see what OP says – Mr. 0xCa7 May 06 '21 at 15:07
  • The "/" was moving through the directory tree. I answer was appending Main_Folder/Export directory to Python's path – colinxu2020 May 09 '21 at 09:21