Python 从兄弟目录导入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4542352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:14:53  来源:igfitidea点击:

Import from sibling directory

pythonpathdirectoryparentsys

提问by skylerl

I have a Python class called "ClassA" and another Python class which is supposed to import ClassA which is "ClassB". The directory structure is as follows:

我有一个名为“ClassA”的 Python 类和另一个应该导入 ClassA 的 Python 类,即“ClassB”。目录结构如下:

MainDir
../Dir
..../DirA/ClassA
..../DirB/ClassB

How would I use sys.pathso that ClassB can use ClassA?

我将如何使用sys.path以便 ClassB 可以使用 ClassA?

采纳答案by Keith

You really should be using packages. Then MainDir is placed at a point in the file system on sys.path (e.g. .../site-packages), then you can say in ClassB:

你真的应该使用包。然后将 MainDir 放置在文件系统中 sys.path 上的某个点(例如 .../site-packages),然后您可以在 ClassB 中说:

from MainDir.Dir.DirA import ClassA # which is actually a module

You just have to place files named __init__.pyin each directory to make it a package hierarchy.

您只需要__init__.py在每个目录中放置命名的文件即可使其成为包层次结构。

回答by crazylammer

You can use relative import(example from link, current module - A.B.C):

您可以使用相对导入(例如来自链接,当前模块 - A.B.C):

from . import D                 # Imports A.B.D
from .. import E                # Imports A.E
from ..F import G               # Imports A.F.G

回答by Remi

as a literal answer to the question 'Python Import from parent directory':

作为问题“从父目录导入 Python”的字面答案:

to import 'mymodule' that is in the parent directory of your current module:

导入当前模块的父目录中的“mymodule”:

import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir) 
import mymodule

editUnfortunately, the __file__attribute is not always set. A more secure way to get the parentdir is through the inspect module:

编辑不幸的是,该__file__属性并不总是设置。获取 parentdir 的更安全方法是通过检查模块:

import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)