简体   繁体   English

从 github repo 下载并从 repo 中导入 .py 文件以供使用

[英]Download from github repo and import .py file from the repo for usage

I'm working on a project that needs some utility functions from a open-source git repo.我正在开发一个项目,该项目需要来自开源 git 存储库的一些实用功能。 Currently, I download the utilities function locally and import it in my python code like this:目前,我在本地下载实用程序函数并将其导入到我的 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

However, I want to automate this process:但是,我想自动化这个过程:

say, it can download the needed utilities from: https://github.com/SpaceNetChallenge/utilities.git比如说,它可以从以下位置下载所需的实用程序: https : //github.com/SpaceNetChallenge/utilities.git

to a given path and import from that path when running the code.到给定的路径并在运行代码时从该路径导入。

Thank you!谢谢!

There are several ways you could download a repo from github from python.您可以通过多种方式从 Python 的 github 下载存储库。 Here's a couple, and I'm sure there are more:这是一对,我相信还有更多:

1: shell out to git, or: 2: download a tgz from github and unpack it 1: shell out to git, or: 2: 从github下载一个tgz并解压

For the first way, do something like this (untested):对于第一种方式,请执行以下操作(未经测试):

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

For the second way (tgz), use urllib.request (also untested):对于第二种方式 (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')

In both cases, you'll probably want to check that it's not already downloaded, so it doesn't re-install every time.在这两种情况下,您可能都需要检查它是否尚未下载,因此不会每次都重新安装。 And of course add lots of error checking.当然,还要添加大量的错误检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM