首页 > 解决方案 > 从 github repo 下载并从 repo 导入 .py 文件以供使用

问题描述

我正在开发一个需要来自开源 git 存储库的一些实用程序功能的项目。目前,我在本地下载实用程序函数并将其导入到我的 python 代码中,如下所示:

path_to_spacenet_utils = 'path/to/my/local/satellite_project/utilities'
sys.path.insert(0,path_to_spacenet_utils)
from spacenetutilities import geoTools as gT

但是,我想自动化这个过程:

比如说,它可以从以下网址下载所需的实用程序:https ://github.com/SpaceNetChallenge/utilities.git

到给定路径并在运行代码时从该路径导入。

谢谢!

标签: pythongit

解决方案


有几种方法可以从 python 的 github 下载 repo。这是一对,我相信还有更多:

1:shell out 到 git,或者: 2:从 github 下载一个 tgz 并解压

对于第一种方法,做这样的事情(未经测试):

import os, subprocess
os.chdir('some dir')
url = `https://github.com/SpaceNetChallenge/utilities.git`
subprocess.call('git clone "{}" spacenetV3'.format(url))

对于第二种方式(tgz),使用urllib.request(也未经测试):

import urllib.request, subprocess
url = 'https://github.com/SpaceNetChallenge/utilities/archive/spacenetV3.zip'  
urllib.request.urlretrieve(url, 'spacenetV3.zip')  
subprocess.call('unzip spacenetV3.zip')

在这两种情况下,您可能都需要检查它是否尚未下载,因此不会每次都重新安装。当然还要添加很多错误检查。


推荐阅读