我想从位于当前目录之上的文件中的类继承。

是否可以相对导入该文件?


当前回答

现在是2022年,没有一个答案真的对我有用。下面是最后奏效的方法

import sys
sys.path.append('../my_class')
import my_class

我的目录结构:

src ——my_class.py 笔记本电脑 ——mynotebook.ipynb

我从mynotebook.ipynb导入my_class。

其他回答

从一个恰好比当前目录高一级的目录导入模块:

from .. import module

运行python /myprogram/submodule/mymodule.py,导入/myprogram/mainmodule.py,例如via

from mainmodule import *

在Linux上(例如,在python Docker映像中),我必须将程序根目录添加到PYTHONPATH:

export PYTHONPATH=/myprogram

从…import subpkg2

根据Python文档:当在包层次结构中,使用两个点,就像import语句doc说的那样:

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

PEP 328涉及绝对/相对进口。

@alex-martelli用pathlib优化的答案:

import pathlib
import sys

_parentdir = pathlib.Path(__file__).parent.parent.resolve()
sys.path.insert(0, str(_parentdir))

import module_in_parent_dir

sys.path.remove(str(_parentdir))
import sys
sys.path.append("..") # Adds higher directory to python modules path.