简体   繁体   English

从父目录中的文件导入类

[英]Importing class from file in parent directory

I have python code that is structured like this: 我有如下结构的python代码:

src
--->commoncode.py
--->folder1
    --->file1.py
--->folder2
    --->file2.py
--->folder3
    --->file3.py

I want to use the code that is in commoncode.py in the files fileN.py. 我想使用文件fileN.py中commoncode.py中的代码。 I have tried including from . import commoncode 我试过了from . import commoncode from . import commoncode but that does not work ( ImportError: cannot import name 'commoncode' ). from . import commoncode但是不起作用( ImportError: cannot import name 'commoncode' )。

I am able to use the code with import commoncode if I include a symlink in each of the subfolders but that seems hacky and sort of defeats the purpose of having common code. 如果我在每个子文件夹中都包含一个符号链接,则可以将代码与import commoncode一起使用,但是这似乎很hacky,有点违反了使用通用代码的目的。

The only code in commoncode.py right now is class commoncode(): . 现在,commoncode.py中唯一的代码是class commoncode():

Let me know if there is any information that I can further provide that would be useful. 让我知道是否有我可以进一步提供的有用信息。

Since you're not using packages, one way is to modify your path: 由于您没有使用包,因此一种方法是修改路径:

import sys
sys.path.insert(0, "..")

from commoncode import <whatever>

# Now you can access imported symbols from commoncode.py

usually when importing you need to import as follows, 通常在导入时,您需要按以下方式进行导入,

from (Name of the module) import (name of the class within the module). 从(模块名称)import(模块内类的名称)。

so in your case, if I understood correctly I believe it would be: 因此,就您而言,如果我理解正确,我相信它将是:

from (Name of the common code module) import commoncode. 从(公共代码模块的名称)导入公共代码。

at the top of any of your modules you wish to use commoncode in, this is how it would be imported. 在要使用commoncode的任何模块的顶部,这就是导入方式。

Please make sure that you haven't missed any capital or lowercase letters as well, as it is case sensitive when you import. 请确保您也不要错过任何大写或小写字母,因为导入时区分大小写。 Hope this could be of some help. 希望这会有所帮助。

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

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