我运行的是Python 2.5。

这是我的文件夹树:

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

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

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

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


当前回答

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

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

其他回答

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

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

from ...module_name import *

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

from ..module_name import *

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

from ...module_name.another_module import *

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

在我看来,你并不真的需要导入父模块。让我们假设在nib.py中有func1()和data1,你需要在life.py中使用

nib.py

import simulations.life.life as life
def func1():
   pass
data1 = {}
life.share(func1, data1)

life.py

func1 = data1 = None

def share(*args):
   global func1, data1
   func1, data1 = args

现在您可以访问life.py中的func1和data。当然,在尝试使用它们之前,你必须小心地在life.py中填充它们,

这个问题似乎与模块位于父目录或类似的内容无关。

您需要将包含ptdraft的目录添加到PYTHONPATH

您说导入nib与您一起工作,这可能意味着您将ptdraft本身(而不是其父)添加到PYTHONPATH。

你可以在“模块搜索路径”中使用OS依赖路径。路径。 因此,您可以轻松地添加如下父目录

import sys
sys.path.insert(0,'..')

如果要添加父-父目录,

sys.path.insert(0,'../..')

这在python2和python3中都适用。

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