简体   繁体   中英

Import module from parent directory in python

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 ?

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:

  1. In terminal, cd to the directory where common directory is there.
  2. Run export PYTHONPATH=${PWD}
  3. Change your imports to start from common, for example:
from common import log
from common import file
from common.conf.myconf import something
  1. 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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM