简体   繁体   English

从外部目录导入 python 库

[英]Importing python libraries from outside directory

I am trying to import python files which have been developed.我正在尝试导入已开发的 python 文件。 Initially, when all files were in the same directory then I there was no problems with them.最初,当所有文件都在同一个目录中时,我对它们没有任何问题。 However, I decided to split projects to dedicated directories.但是,我决定将项目拆分到专用目录。 After that, I am unable to import files anymore.之后,我无法再导入文件。

My file structure is similar to the following:我的文件结构类似于以下内容:

dirFoo\
    mainFoo1.py
dirFoo\
    mainFoo2.py
dirFooCommon\
    commonFoo.py
    commonFoo2.py

Initially, I was trying to change the import path of my mainFoo1.py and do: from dirFooCommon import commonFoo .最初,我试图更改 mainFoo1.py 的导入路径并执行: from dirFooCommon import commonFoo However, that approach gave me the following error: ModuleNotFoundError: No module named 'common'.但是,这种方法给了我以下错误:ModuleNotFoundError: No module named 'common'。

Apart from that, I tried to use imp.load_source which seems that is working.除此之外,我尝试使用imp.load_source似乎可行。 Unfortunately, this is generating so additional problems.不幸的是,这会产生额外的问题。 For example what if some of the commonFoo.py libraries must include others?例如,如果某些 commonFoo.py 库必须包含其他库怎么办? In this case, each of them needs to use an absolute project path, which will be a problem when I will try to use common libraries in any other place.在这种情况下,他们每个人都需要使用绝对项目路径,当我尝试在任何其他地方使用公共库时,这将是一个问题。

Do you have an idea what should I do to include my common libraries to my main projects?你知道我应该怎么做才能将我的公共库包含到我的主要项目中吗?

You can use this folder structure that will allow you to call each package and module properly.您可以使用此文件夹结构,以便正确调用每个 package 和模块。

dirFoo\  <=== This is a package know 
    __init__.py 
    mainFoo1.py
dirFoo2\  <==== Change the name or you will have namespace issue
    __init__.py
    mainFoo2.py
dirFooCommon\ <=== This is a package know 
    __init__.py
    commonFoo.py
    commonFoo2.py

So in mainFoo1.py you can call commonFoo.py like this所以在mainFoo1.py你可以像这样调用commonFoo.py

import sys
sys.path.append("/path/to/dirFooCommon")

from dirFooCommon import commonFoo

To replace sys.path.append you can also add the folder in your PYTHONPATH .要替换sys.path.append您还可以在PYTHONPATH中添加文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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