How to import python file from git submodule

2019-02-16 09:39发布

问题:

I've a project which uses git submodules. In my python file I want to use functions from another python file in the submodule project.

In order to work I had to add the init.py file to all subfolders in the path. My folder tree is the following:

myproj
├── gitmodules
│   ├── __init__.py
│   ├── __init__.pyc
│   └── mygitsubmodule
│       ├── __init__.py
│       ├── __init__.pyc
│       └── file.py
└── myfile.py

Is there any way to make it work without touching mygitsubmodule ?

Thanks

回答1:

you can add to sys.path in the file you want to be able to access the module, something like:

import sys
sys.path.append("/home/me/myproj/gitmodules")
import mygitsubmodule

EDIT: This example is adding a path as a raw string to make it clear what's happening. You should really use the more sophisticated, system independent methods described below to determine and assemble the path.

Also, I have found it better, when I used this method, to use sys.path.insert(1, .. as some functionality seems to rely of sys.path[0] being the starting directory of the program.