我想从位于当前目录之上的文件中的类继承。
是否可以相对导入该文件?
我想从位于当前目录之上的文件中的类继承。
是否可以相对导入该文件?
当前回答
现在是2022年,没有一个答案真的对我有用。下面是最后奏效的方法
import sys
sys.path.append('../my_class')
import my_class
我的目录结构:
src ——my_class.py 笔记本电脑 ——mynotebook.ipynb
我从mynotebook.ipynb导入my_class。
其他回答
从一个恰好比当前目录高一级的目录导入模块:
from .. import module
import sys
sys.path.append("..") # Adds higher directory to python modules path.
运行python /myprogram/submodule/mymodule.py,导入/myprogram/mainmodule.py,例如via
from mainmodule import *
在Linux上(例如,在python Docker映像中),我必须将程序根目录添加到PYTHONPATH:
export PYTHONPATH=/myprogram
@gimel's answer is correct if you can guarantee the package hierarchy he mentions. If you can't -- if your real need is as you expressed it, exclusively tied to directories and without any necessary relationship to packaging -- then you need to work on __file__ to find out the parent directory (a couple of os.path.dirname calls will do;-), then (if that directory is not already on sys.path) prepend temporarily insert said dir at the very start of sys.path, __import__, remove said dir again -- messy work indeed, but, "when you must, you must" (and Pyhon strives to never stop the programmer from doing what must be done -- just like the ISO C standard says in the "Spirit of C" section in its preface!-).
下面是一个可能对你有用的例子:
import sys
import os.path
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import module_in_parent_dir
@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))