如何从git子模块导入python文件 [英] How to import python file from git submodule

查看:172
本文介绍了如何从git子模块导入python文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用git子模块的项目.在我的python文件中,我想使用子模块项目中另一个python文件中的函数.

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.

为了工作,我必须将 init .py文件添加到路径中的所有子文件夹中.我的文件夹树如下:

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

有什么办法可以使它在不接触mygitsubmodule的情况下工作?

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

谢谢

推荐答案

您可以将其添加到要访问该模块的文件的sys.path中,例如:

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

此示例将路径添加为原始字符串,以使其清楚正在发生的事情.您确实应该使用下面描述的更复杂,与系统无关的方法来确定和组装路径.

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.

此外,当我使用此方法时,我发现使用sys.path.insert(1, ..更好,因为某些功能似乎依赖于sys.path[0]作为程序的起始目录.

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.

这篇关于如何从git子模块导入python文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆