我运行的是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.path.append(“. . /”)
其他回答
不太懂python 2。 在python 3中,父文件夹可以按如下方式添加:
import sys
sys.path.append('..')
...然后我们可以从中导入模块
我有一个专门针对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
在我看来,你并不真的需要导入父模块。让我们假设在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中填充它们,
你可以在“模块搜索路径”中使用OS依赖路径。路径。 因此,您可以轻松地添加如下父目录
import sys
sys.path.insert(0,'..')
如果要添加父-父目录,
sys.path.insert(0,'../..')
这在python2和python3中都适用。
与过去的答案风格相同,但行数更少:P
import os,sys
parentdir = os.path.dirname(__file__)
sys.path.insert(0,parentdir)
文件返回您正在工作的位置