我运行的是Python 2.5。

这是我的文件夹树:

ptdraft/
  nib.py
  simulations/
    life/
      life.py

(我在每个文件夹中都有__init__.py,为了可读性,这里省略了)

我如何从生命模块内导入nib模块?我希望不需要修改sys.path就可以做到。

注意:正在运行的主模块在ptdraft文件夹中。


当前回答

相对进口(如从..Import mymodule)只在包中工作。 导入当前模块父目录中的'mymodule':

import os
import sys
import inspect

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir) 

import mymodule

编辑:__file__属性并不总是给定的。我现在建议使用inspect模块来检索当前文件的文件名(和路径),而不是使用os.path.abspath(__file__)

其他回答

在Jupyter笔记本上(用Jupyter LAB或Jupyter Notebook打开)

只要你在木星笔记本上工作,这个简短的解决方案可能会有用:

%cd ..
import nib

即使没有__init__.py文件,它也能工作。

我在Linux和Windows 7上用Anaconda3测试了它。

相对进口(如从..Import mymodule)只在包中工作。 导入当前模块父目录中的'mymodule':

import os
import sys
import inspect

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir) 

import mymodule

编辑:__file__属性并不总是给定的。我现在建议使用inspect模块来检索当前文件的文件名(和路径),而不是使用os.path.abspath(__file__)

下面是一个更通用的解决方案,它将父目录包含到sys. conf中。路径(适用于我):

import os.path, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

在删除了一些系统路径黑客后,我认为添加它可能是有价值的

我喜欢的解决方案。

注意:这是一个框架挑战-没有必要在代码中做。

假设有一棵树,

project
└── pkg
    └── test.py

test.py包含什么

import sys, json; print(json.dumps(sys.path, indent=2)) 

使用路径执行只包括包目录

python pkg/test.py
[
  "/project/pkg",
 ...
]

但是使用module参数会包含项目目录

python -m pkg.test
[
  "/project",
  ...
]

现在,从项目目录导入的所有内容都可以是绝对的。不需要再耍花招了。

这适用于我从更高的文件夹导入东西。

import os
os.chdir('..')