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?
CodePudding user response:
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
CodePudding user response:
If you want to run myconf.py as the entry point you can add the parent folder of common to sys.path.
myconf.py
import sys
from os.path import dirname
sys.path.append(dirname(dirname(dirname(__name__))))
from common import file
data = file.myfunction()
print (data )
log.py
from common import log
def myfunction():
return "dummy"
