I want to import a class
from a python file in a directory in the parent directory.
This is my current folder structure:
│ run_simulation_from_parent.py
│ __init__.py
│
├───.vscode
│ launch.json
│ settings.json
│
├───mod
│ │ mods.py
│ │ __init__.py
│ │
│ └───__pycache__
│ __init__.cpython-37.pyc
│
├───sim
│ │ run_simulation.py
│ │ __init__.py
│ │
│ └───__pycache__
│ __init__.cpython-37.pyc
│
└───__pycache__
__init__.cpython-37.pyc
The file mod/mods.py
contains the following class:
class Objective:
"""Objective function class"""
def __init__(self, x):
self.x = x
The file sim/run_simulation.py
contains:
from mod.mods import Objective
x = 5
obj = Objective(x)
When I try to run this I get the following error:
File "sim/run_simulation.py", line 1, in <module>
from mod.mods import Objective
ModuleNotFoundError: No module named 'mod'
In visual studio code it does autofill when I start typing mod.mods
and import Objective
When I run run_simulation_from_parent.py
with the following content I have no problems:
from mod.mods import Objective
x = 5
obj = Objective(x)
print(obj.x)
How can I do this from the directory sim
? I already tried the following:
- Use
from ..mod.mods import Objective
to run_simulation.py Use init.py files with the following content:
import os, sys sys.path.append(os.path.dirname(os.path.realpath(__file__)))
Without the
__init__.py
files
Edit: I run the file from visual studio code where I start in the parent directory. I also tried from the command line in windows from the sim folder where I used
python run_simulation.py