我运行的是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文件夹中。
当前回答
你可以在“模块搜索路径”中使用OS依赖路径。路径。 因此,您可以轻松地添加如下父目录
import sys
sys.path.insert(0,'..')
如果要添加父-父目录,
sys.path.insert(0,'../..')
这在python2和python3中都适用。
其他回答
你可以在“模块搜索路径”中使用OS依赖路径。路径。 因此,您可以轻松地添加如下父目录
import sys
sys.path.insert(0,'..')
如果要添加父-父目录,
sys.path.insert(0,'../..')
这在python2和python3中都适用。
我有一个专门针对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
二线最简解
import os, sys
sys.path.insert(0, os.getcwd())
如果父目录是你的工作目录,你想从子脚本调用另一个子模块。
您可以在任何脚本中从父目录导入所有子模块并执行
python child_module1/child_script.py
导入系统 sys.path.append(“. . /”)
与过去的答案风格相同,但行数更少:P
import os,sys
parentdir = os.path.dirname(__file__)
sys.path.insert(0,parentdir)
文件返回您正在工作的位置