我运行的是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文件夹中。
当前回答
我发现下面的方法可以从脚本的父目录导入包。在这个例子中,我想从app.db包中导入env.py中的函数。
.
└── my_application
└── alembic
└── env.py
└── app
├── __init__.py
└── db
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
其他回答
不太懂python 2。 在python 3中,父文件夹可以按如下方式添加:
import sys
sys.path.append('..')
...然后我们可以从中导入模块
虽然原作者可能不再寻找解决方案,但为了完整,有一个简单的解决方案。它是像这样运行life.py模块:
cd ptdraft
python -m simulations.life.life
通过这种方式,您可以从nib.py导入任何东西,因为ptdraft目录在路径中。
我有一个专门针对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
我建这个图书馆就是为了做这个。
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
我发现下面的方法可以从脚本的父目录导入包。在这个例子中,我想从app.db包中导入env.py中的函数。
.
└── my_application
└── alembic
└── env.py
└── app
├── __init__.py
└── db
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)