I have a little application on Python3 but it won't run because of module not found. I added __init__.py for all the folders already but it doesn't work. I'm wondering why.
Here's my structure
my_project
|- __init__.py
|
|-- folder
|-code.py
|- __init__.py
|
|-- Makefile
|-- scripts
|- import_data.py
Here's My Makefile
test:
py.test tests/*.py
create_graph:
python scripts/import_data.py
And here's my import_data.py
from folder.code import method
import csv
method()
# doing something here
When I run make create_graph It gives me this.
python scripts/import_data.py
Traceback (most recent call last):
File "scripts/import_data.py", line 1, in
from folder.code import method
ImportError: No module named 'folder'
make: *** [create_graph] Error 1
解决方案
When the import_data.py script is run, the sys.path has my_project/scripts in it, but not my_project , hence python is not able to locate folder package in sys.path .
You should try adding the my_project folder into the PYTHONPATH variable , this would allow you to access folder.code from anywhere. Example for BASH -
export PYTHONPATH=:$PYTHONPATH
If you cannot make such environment variable changes , then programmatically, before trying to import folder.code , you can add the my_project folder to sys.path variable. For that you can use __file__ to get the filename of the script, and then get the directory name from that using os.path.dirname() and then get its parent using os.path.join and os.path.abspath Example your import_data.py may look like -
import sys
import os.path
parent = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) #this should give you absolute location of my_project folder.
sys.path.append(parent)
from folder.code import method
import csv
method()