我运行的是Python 2.5。

这是我的文件夹树:

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

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

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

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


当前回答

虽然这是违反所有规则的,但我还是想提一下这种可能性:

您可以先将文件从父目录复制到子目录。接下来导入它,然后删除复制的文件:

例如,在life.py中:

import os
import shutil

shutil.copy('../nib.py', '.')
import nib
os.remove('nib.py')

# now you can use it just fine:
nib.foo()

当然,当nibs尝试使用相对导入/路径导入/读取其他文件时,可能会出现一些问题。

其他回答

相对进口(如从..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__)

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

import os
os.chdir('..')

你可以使用相对导入(python >= 2.5):

from ... import nib

(Python 2.5新增功能)PEP 328:绝对和相对导入

编辑:增加了另一个点。“去送两个包裹

我有一个专门针对git存储库的解决方案。

首先,我使用sys.path.append('..')和类似的解决方案。如果你导入的文件本身使用sys.path.append('..')导入文件,这会导致特别的问题。

然后我决定总是附加git存储库的根目录。在一行中是这样的:

sys.path.append(git.Repo('.', search_parent_directories=True).working_tree_dir)

或者更详细一点,像这样:

import os
import sys
import git
def get_main_git_root(path):
    main_repo_root_dir = git.Repo(path, search_parent_directories=True).working_tree_dir
    return main_repo_root_dir
main_repo_root_dir = get_main_git_root('.')
sys.path.append(main_repo_root_dir)

对于最初的问题:根据存储库的根目录,导入将是

import ptdraft.nib

or

import nib

在Linux系统中,您可以创建从“life”文件夹到nib.py文件的软链接。然后,你可以像这样简单地导入它:

import nib