我运行的是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

其他回答

我认为你可以在那个特定的例子中尝试这样做,但在python 3.6.3中

如果将模块文件夹添加到PYTHONPATH中失败,则可以修改sys. conf文件。Python解释器在你的程序中搜索要导入的模块的路径列表,Python文档说:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations: the directory containing the input script (or the current directory). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). the installation-dependent default. After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended.

知道了这一点,你可以在程序中执行以下操作:

import sys
# Add the ptdraft folder path to the sys.path list
sys.path.append('/path/to/ptdraft/')

# Now you can import your module
from ptdraft import nib
# Or just
import ptdraft

与图书馆合作。 创建一个名为nib的库,使用setup.py安装它,让它驻留在站点包中,这样你的问题就解决了。 你不需要把你做的所有东西都装在一个包里。把它拆成碎片。

在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