I have python script in following directory structure
common/
log.py
file.py
__init__.py
conf/
myconf.py
__init__.py
here is my myconf.py
from common import file
data = file.myfunction()
print (data )
here is file.py
import log
myfunction():
return "dummy"
when i run my myconf.py i get below error
ModuleNotFoundError: No module named 'log
how to handle import log in my myconf.py?
2 Answers 2
One solution is to add common to your PYTHONPATH and run everything from there. This is the best practice and the best solution in my opinion to handle the imports.
To do so:
- In terminal, cd to the directory where common directory is there.
- Run
export PYTHONPATH=${PWD} - Change your imports to start from common, for example:
from common import log
from common import file
from common.conf.myconf import something
- If you want to run a file, run it from the root:
python common/conf/myconf.py
This way you will never have any import error and all your imports are extremely clear and readable cause they all start from common
2 Comments
python -m common.conf.myconf and you then don't need to use PYTHONPATHIf you want to run myconf.py as the entry point from anywhere without caring about PYTHONPATH you can add the parent folder of common to sys.path.
myconf.py
if __name__ == '__main__':
import sys; from os.path import dirname
sys.path.append(dirname(dirname(dirname(__file__))))
from common import file
data = file.myfunction()
print(data)
log.py
from common import log
def myfunction():
return "dummy"
1 Comment
sys.path is not a good practice: stackoverflow.com/questions/51146723/…...