我运行的是Python 2.5。

这是我的文件夹树:

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

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

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

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


当前回答

二线最简解

import os, sys
sys.path.insert(0, os.getcwd()) 

如果父目录是你的工作目录,你想从子脚本调用另一个子模块。

您可以在任何脚本中从父目录导入所有子模块并执行

python child_module1/child_script.py

其他回答

与过去的答案风格相同,但行数更少:P

import os,sys
parentdir = os.path.dirname(__file__)
sys.path.insert(0,parentdir)

文件返回您正在工作的位置

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

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

不太懂python 2。 在python 3中,父文件夹可以按如下方式添加:

import sys 
sys.path.append('..')

...然后我们可以从中导入模块

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

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

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

from ... import nib

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

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