How do I import helpers in script.py ?
Python version : 3.6.8
directory structure :
main_folder
|
| folder1
| | folder2
| | | script.py
|
| helpers.py
script.py :
from helpers import markdown
command :
python3 folder1/folder2/script.py
error :
ModuleNotFoundError: No module named 'helpers'
CodePudding user response:
You can add the following to the top of script.py
to correctly set the path.
import sys
import os
module_path = os.path.abspath(os.getcwd())
if module_path not in sys.path:
sys.path.append(module_path)
Keep the rest as is and it should work
CodePudding user response:
If you execute your script with python3 folder1/folder2/script.py
then Python will not be aware of the package structure. The basis for imports will be folder2
so it is not able to find your helper module. To fix this, use python3 -m folder1.folder2.script
instead. This will let you import modules starting from main_folder
.