How to import a module from a different folder?

倾然丶 夕夏残阳落幕 提交于 2020-03-14 07:52:46

问题


I have a project which I want to structure like this:

myproject
  __init__.py
  api
    __init__.py
    api.py
  backend
    __init__.py
    backend.py
  models
    __init__.py
    some_model.py

Now, I want to import the module some_model.py in both api.py and backend.py. How do I properly do this?

I tried:

from models import some_model

but that fails with ModuleNotFoundError: No module named 'models'.

I also tried:

from ..models import some_model

which gave me ValueError: attempted relative import beyond top-level package.

What am I doing wrong here? How can I import a file from a different directory, which is not a subdirectory?


回答1:


Firstly, this import statement:

from models import some_model

should be namespaced:

# in myproject/backend/backend.py or myproject/api/api.py
from myproject.models import some_model

Then you will need to get the directory which contains myproject, let's call this /path/to/parent, into the sys.path list. You can do this temporarily by setting an environment variable:

export PYTHONPATH=/path/to/parent

Or, preferably, you can do it by writing a setup.py file and installing your package. Follow the PyPA packaging guide. After you have written your setup.py file, from within the same directory, execute this to setup the correct entries in sys.path:

pip install --editable .



回答2:


Unfortunately, Python will only find your file if your file is in the systems path. But fear not! There is a way around this!

Using python's sys module, we can add a directory to the path just while Python is running, and once Python stops running, it will remove it from the path.

You can do this by:

import sys
sys.path.insert(0, '/path/to/application/app/folder')
import [file]

It is important to import sys and set the directory path before you import the file however.

Good luck!

Jordan.




回答3:


Although the above answers are all kind of correct, I found one more answer, which I want to add for completeness. Apparently, the directory in which the originally executed script resides and it's subdirectories are automativally added to the path list.

This means that if you create a start script(e.g. main.py) to your projects root, which will later execute all the other modules (api.py and backend.py in my case) then the above method using

from models import some_model

will work.




回答4:


This was answered here: Importing files from different folder, in a number of complicated ways. You can also use:

import os

os.chdir('Your/New/Directory")

import whatever

Which is very inelegant but does the job. Remember to change back if you need more from the previous directory.

Allen



来源:https://stackoverflow.com/questions/49039436/how-to-import-a-module-from-a-different-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!