我运行的是Python 2.5。

这是我的文件夹树:

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

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

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

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


当前回答

在我看来,你并不真的需要导入父模块。让我们假设在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中填充它们,

其他回答

我有一个专门针对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

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

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

%cd ..
import nib

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

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

二线最简解

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

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

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

python child_module1/child_script.py

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

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

from ... import nib

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

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