[英]Using git submodule to import a python project
(I realise there are a lot of questions on StackOverflow relating to python relative imports; I suspect also that I'm doing this all wrong; but here goes anyway ..) (我意识到 StackOverflow 上有很多与 python 相对导入相关的问题;我也怀疑我做错了;但无论如何都在这里..)
I have a python project (mysubmod) organised as follows:我有一个 python 项目 (mysubmod) 组织如下:
/__init__.py
/lib
- /__init__py
- /foobar.py
/models
- /__init__.py
- /hello.py
Importantly:重要的:
I then have a second project (myproj) into which I've imported mysubmod as a git submodule;然后我有第二个项目 (myproj),我将 mysubmod 作为 git 子模块导入其中; myproj is now organised as follows -
myproj 现在组织如下 -
/mysubmod
/scripts
- /__init__.py
- /__test.py
Where:在哪里:
However when I run /scripts/test.py from the command line, the interpreter now complains that mysubmod/models/hello.py can no longer find lib.foobar.但是,当我从命令行运行 /scripts/test.py 时,解释器现在抱怨 mysubmod/models/hello.py 无法再找到 lib.foobar。
Reload.重新加载。
Changed mysubmod/models/hello.py so it now imports ..lib.foobar改变了 mysubmod/models/hello.py 所以它现在导入 ..lib.foobar
Now I can run /scripts/test.py without complaint, but I can no longer run any of the submod scripts as files from the command line;现在我可以毫无怨言地运行 /scripts/test.py,但是我不能再从命令行将任何 submod 脚本作为文件运行; I can only run them as modulles using the python -m option.
我只能使用 python -m 选项将它们作为模块运行。
Also I can no longer run the submod project files on a standalone basis, even with the -m option, as the interpreter complains about 'Attempted relative import beyond toplevel package';此外,即使使用 -m 选项,我也无法再独立运行 submod 项目文件,因为解释器抱怨“尝试在顶级包之外进行相对导入”; I have to go up a directory level, ie can only really run mysubmod from the myproj root (where it has mysubmod as the root level directory).
我必须上升到一个目录级别,即只能从 myproj 根目录(其中将 mysubmod 作为根级别目录)真正运行 mysubmod。
This all seems pretty unsatisfactory.这一切似乎都不尽如人意。 I want to be able to:
我希望能够:
Does anyone have any views on how to do this ?有没有人对如何做到这一点有任何看法? Any views on best practices with respect to git submodule and python ?
关于 git submodule 和 python 的最佳实践有什么看法?
Thanks.谢谢。
OK the answer is (after many wrong turns)好的答案是(经过多次错误的转弯)
This way, the package structure is maintained whether you are working with the submod as a submodule or on a standalone basis.这样,无论您是将 submod 作为子模块还是独立使用,都可以保持包结构。
You could also add mysubmod
to sys.path
when you starting your myproj
.您还可以在启动
myproj
时将mysubmod
添加到sys.path
。 Then mysubmod/models/hello.py
will find lib.foobar
.然后
mysubmod/models/hello.py
会找到lib.foobar
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.