我运行的是Python 2.5。

这是我的文件夹树:

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

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

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

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


当前回答

我建这个图书馆就是为了做这个。

https://github.com/fx-kirin/add_parent_path

# Just add parent path
add_parent_path(1)

# Append to syspath and delete when the exist of with statement.
with add_parent_path(1):
   # Import modules in the parent path
   pass

其他回答

导入系统 sys.path.append(“. . /”)

上面提到的解决方案也很好。这个问题的另一个解决方案是

如果你想从顶级目录导入任何东西。然后,

from ...module_name import *

此外,如果您想从父目录导入任何模块。然后,

from ..module_name import *

此外,如果您想从父目录导入任何模块。然后,

from ...module_name.another_module import *

通过这种方式,如果您愿意,您可以导入任何特定的方法。

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

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

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

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

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

例如,在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尝试使用相对导入/路径导入/读取其他文件时,可能会出现一些问题。