我运行的是Python 2.5。
这是我的文件夹树:
ptdraft/
nib.py
simulations/
life/
life.py
(我在每个文件夹中都有__init__.py,为了可读性,这里省略了)
我如何从生命模块内导入nib模块?我希望不需要修改sys.path就可以做到。
注意:正在运行的主模块在ptdraft文件夹中。
我运行的是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))
其他回答
你可以在“模块搜索路径”中使用OS依赖路径。路径。 因此,您可以轻松地添加如下父目录
import sys
sys.path.insert(0,'..')
如果要添加父-父目录,
sys.path.insert(0,'../..')
这在python2和python3中都适用。
这适用于我从更高的文件夹导入东西。
import os
os.chdir('..')
我们的文件夹结构:
/myproject
project_using_ptdraft/
main.py
ptdraft/
__init__.py
nib.py
simulations/
__init__.py
life/
__init__.py
life.py
我理解这一点的方式是以包为中心的观点。 包根是ptdraft,因为它是包含__init__.py的最顶层
例如,包中的所有文件都可以使用绝对路径(相对于包根)进行导入 在life.py中,我们简单地有:
import ptdraft.nib
然而,为了包开发/测试目的而运行life.py,而不是python life.py,我们需要使用:
cd /myproject
python -m ptdraft.simulations.life.life
注意,在这一点上,我们根本不需要修改任何路径。
更令人困惑的是,当我们完成ptdraft包时,我们想在一个驱动程序脚本中使用它,它必须在ptdraft包文件夹之外,也就是project_using_ptdraft/main.py,我们需要摆弄路径:
import sys
sys.path.append("/myproject") # folder that contains ptdraft
import ptdraft
import ptdraft.simulations
使用python main.py运行脚本没有问题。
有用的链接:
https://tenthousandmeters.com/blog/python-behind-the-scenes-11-how-the-python-import-system-works/(查看如何使用__init__.py) https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html#running-package-initialization-code https://stackoverflow.com/a/50392363/2202107 https://stackoverflow.com/a/27876800/2202107
如果将模块文件夹添加到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
在Jupyter笔记本上(用Jupyter LAB或Jupyter Notebook打开)
只要你在木星笔记本上工作,这个简短的解决方案可能会有用:
%cd ..
import nib
即使没有__init__.py文件,它也能工作。
我在Linux和Windows 7上用Anaconda3测试了它。