I'm having difficulties making a git submodule work.
I have a project ProjectA
that basically is a mainA.py
file and a subfolder with library files: The mainA.py
contains a MainClass
that is basically what should be called, and Libraries
just contain scripts and classes for computations.
ProjectA/
Libraries/
__init__.py
library1.py
library2.py
__init__.py
mainA.py
In mainA.py
I just do something like:
# content of mainA.py
from Libraries.library1 import ClassA, ClassB
class MainClass:
# do stuff
if __name__ == '__main__':
MainClass()
This just works fine, but I have now a ProjectB
that needs to use the MainClass
from ProjectA
, so I decided to put ProjectA
as a git submodule of ProjectB
git submodule add ProjectA_git_url
ProjectB/
ProjectA/
mainB.py
.gitmodules
However now in mainB.py
I'm trying to import MainClass
from projectA
.
# content of mainB.py
from ProjectA.mainA import MainClass
ModuleNotFoundError: No module named 'Libraries'
I think this happens because now Libraries
is no longer hanging from the root directory, but inside the submodule ProjectA
, so when mainA.py
does:
from Libraries.library1 import ClassA, ClassB
The system cannot find Libraries
. If I change mainA.py
to do:
from ProjectA.Libraries.library1 import ClassA, ClassB
Then it works, but of course I don't want to change anything insise ProjectA
, it is just a Project that should work either standalone or as a submodule of another project
What am I doing wrong? Is there a way to import MainClass
from mainA.py
when ProjectA
is a submodule?
git
is a development tool; you use it during development but not deployment. pip
is a deployment tool; during development you use it to install necessary libraries; during deployment your users use it to install your package with dependencies.
Use submodules when you need something from a remote repository in your development environment. For example, if said remote repository contains Makefile(s) or other non-python files that you need and that usually aren't installed with pip
.
That is, in your case you shouldn't make ProjectA
a submodule of ProjectB
, you should make ProjectA
a Python dependency. Create packages for ProjectA
and ProjectB
and install them separately but allow ProjectB
to import from ProjectA
.
Dependencies are declared in setup.py
or requirements.txt
.
That said, if you insist on using submodules: either you have to manipulate sys.path
yourself or you do relative import in mainA.py
:
from .Libraries.library1 import ClassA, ClassB
将子模块路径添加到 mainB.py 中的系统路径假设您的子模块路径是“../ProjectB/ProjectA” sys.path.append(../ProjectB/ProjectA) 解决问题。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.