【发布时间】:2018-06-29 05:36:00
【问题描述】:
有没有推荐的方法将git与colab集成?
例如,是否可以处理来自 google 源代码库或类似资源的代码?
谷歌驱动器和云存储都不能用于 git 功能。
所以我想知道是否还有办法做到这一点?
【问题讨论】:
有没有推荐的方法将git与colab集成?
例如,是否可以处理来自 google 源代码库或类似资源的代码?
谷歌驱动器和云存储都不能用于 git 功能。
所以我想知道是否还有办法做到这一点?
【问题讨论】:
如果您想克隆一个私有存储库,最快的方法是创建一个personal access token 并仅选择您的应用程序需要的权限。然后 GitHub 的克隆命令如下所示:
!git clone https://git_token@github.com/username/repository.git
【讨论】:
u = 'user0'; p = 'pass0'; !git clone https://$u:$p@github.com/$u/repository.git 这应该可以,{p} {u} 也可以。 (!...应该开始一个新的行。)
@,请将其替换为%40。
from IPython.display import clear_output; u = input(); key = input(); clear_output() 运行 !git clone https://$u:$key@github.com/rohitdavas/reponame.git
机器上安装了git,可以使用!调用shell命令。
例如,克隆一个git 存储库:
!git clone https://github.com/fastai/courses.git
这是一个完整的示例,它克隆存储库并加载存储在其中的 Excel 文件。 https://colab.research.google.com/notebook#fileId=1v-yZk-W4YXOxLTLi7bekDw2ZWZXWW216
【讨论】:
! git clone https://TOKEN@github.com/username/repository.git。
在 Google colab 中克隆您的私有 github 存储库的非常简单易行的方法如下。
import os
from getpass import getpass
import urllib
user = input('User name: ')
password = getpass('Password: ')
password = urllib.parse.quote(password) # your password is converted into url format
repo_name = input('Repo name: ')
cmd_string = 'git clone https://{0}:{1}@github.com/{0}/{2}.git'.format(user, password, repo_name)
os.system(cmd_string)
cmd_string, password = "", "" # removing the password from the variable
【讨论】:
您可以使用 ssh 协议将您的私有存储库与 colab 连接起来
在本地机器上生成 ssh 密钥对,别忘了保留
释义为空,请查看tutorial。
上传到colab,查看下面screenshot
from google.colab import filesuploaded = files.upload()
将 ssh kay 对移动到 /root 并连接到 git
! rm -rf /root/.ssh/*! mkdir /root/.ssh
! tar -xvzf ssh.tar.gz
! cp ssh/* /root/.ssh && rm -rf ssh && rm -rf ssh.tar.gz
! chmod 700 /root/.ssh
! ssh-keyscan gitlab.com >> /root/.ssh/known_hosts! chmod 644 /root/.ssh/known_hosts
! git config --global user.email "email"! git config --global user.name "username"
! ssh git@gitlab.com
验证您的私有存储库,请检查此Per-repository deploy keys。
使用! git@gitlab.com:{account}/{projectName}.git
注意:要使用推送,您必须为
授予写入权限
用于验证 git 服务器的公共 ssh 密钥。
为了保护您的账户用户名和密码,您可以使用getPass并在shell命令中将它们连接起来:
from getpass import getpass
import os
user = getpass('BitBucket user')
password = getpass('BitBucket password')
os.environ['BITBUCKET_AUTH'] = user + ':' + password
!git clone https://$BITBUCKET_AUTH@bitbucket.org/{user}/repository.git
【讨论】:
{user},我收到了一个 400(错误请求),它不会转换为实际的用户名。
你几乎可以使用这个链接: https://qiita.com/Rowing0914/items/51a770925653c7c528f9
作为上述链接的摘要,您应该执行以下步骤:
1- 使用以下命令将您的 google colab 运行时连接到您的 Google 云端硬盘:
from google.colab import drive
drive.mount('/content/drive')
它需要一个身份验证过程。随心所欲。
2-在current directory那里设置你要克隆Git项目的路径:
在我的例子中:
path_clone = "drive/My Drive/projects"
%cd path_clone
不要忘记在cd 命令的开头使用!。
3- 克隆 Git 项目:
!git clone <Git project URL address>
现在您将在您的 Google Drive 中的 projects 文件夹中拥有克隆的 Git 项目(它也连接到您的 Google Colab 运行时机器)
4- 转到您的 Google 云端硬盘(使用浏览器等),然后转到“项目”文件夹并打开您要在 Google Colab 中使用的 .ipynb 文件。 p>
5-现在您有了 Google Colab 运行时和您想要使用的 .ipynb,它也连接到您的 Google 云端硬盘,并且所有克隆的 git 文件都在 Colab 运行时的存储中.
注意:
1- 检查您的 Colab 运行时是否已连接到 Google 云端硬盘。如果未连接,只需重复上述第 1 步。
2- 使用“pwd”和“cd”命令仔细检查 current directory 是否与 google Drive 中克隆的 git 项目相关(上面的第 2 步)。
【讨论】:
%cd 而不是!cd
使用git同步colab与github或gitlab的三步。
生成一个私钥-公钥对。将私钥复制到系统clibboard以供步骤2使用。根据需要将公钥粘贴到github或gitlab。
在 Linux 中,ssh-keygen 可用于在 ~/.ssh 中生成密钥对。生成的私钥在文件 id_rsa 中,公钥在文件 id_rsa.pub 中。
在 Colab 中,执行
key = \
'''
paste the private key here
(your id_rsa or id_ecdsa file in the .ssh directory, e.g.
-----BEGIN EC PRIVATE KEY-----
M..............................................................9
...............................................................J
..................................==
-----END EC PRIVATE KEY-----
'''
! mkdir -p /root/.ssh
with open(r'/root/.ssh/id_rsa', 'w', encoding='utf8') as fh:
fh.write(key)
! chmod 600 /root/.ssh/id_rsa
! ssh-keyscan github.com >> /root/.ssh/known_hosts
# test setup
! ssh -T git@github.com
# if you see something like "Hi ffreemt! You've successfully
# authenticated, but GitHub does not provide shell access."
# you are all set. You can tweak .ssh/config for multiple github accounts
像往常一样使用 git 拉/推。
同样的想法可以用于 colab 和 HostA 之间的 rsync(或 ssh),只需稍作改动:
生成一个私钥-公钥对。将私钥复制到系统clibboard,用于步骤2。将公钥粘贴到HostA中.ssh中的authorized_keys。
在 Colab 中,执行
key = \
'''
paste the private key here
'''
! mkdir -p /root/.ssh
with open(r'/root/.ssh/id_rsa', 'w', encoding='utf8') as fh:
fh.write(key)
! chmod 600 /root/.ssh/id_rsa
! ssh -oStrictHostKeyChecking=no root@HostA hostnam # ssh-keyscan
HostA >> /root/.ssh/known_hosts 似乎不适用于 IP。
【讨论】:
将私有仓库克隆到 google colab:
生成令牌:
Settings -> Developer settings -> Personal access tokens -> Generate new token
复制令牌并克隆 repo(相应地替换 username 和 token)
!git clone https://username:token@github.com/username/repo_name.git
【讨论】:
2021 年 9 月更新 — 出于安全原因,现在不推荐使用 github 使用密码。请改用
Personal Access Token— 转到 github.com -> 设置 -> 开发人员设置 -> 个人访问令牌并为所需目的生成令牌。对于本教程中提到的所有任务,请使用此密码代替您的密码!
更多详情你也可以看我在 Medium 上的文章:https://medium.com/geekculture/using-git-github-on-google-colaboratory-7ef3b76fe61b
没有一个答案能提供像这样直接而直接的答案:
这可能就是您正在寻找的答案..
在 colab 上适用于公共和私有存储库,并且不要更改/跳过任何步骤:(全部替换 {vars})
TL;DR 完成流程:
!git clone https://{your_username}:{your_password}@github.com/{destination_repo_username}/{destination_repo_projectname}.git
%cd /content/{destination_repo_username}
!git config --global user.name "{your_username}"
!git config --global user.email "{your_email_id}"
!git config --global user.password "{your_password}"
进行更改然后运行:
!git add .
!git commit -m "{Message}"
!git push
!git clone https://{your_username}:{your_password}@github.com/{destination_repo_username}/{destination_repo_projectname}.git
对于 jupyter 笔记本,使用 line magic 命令 %cd 将目录更改为 {destination_repo_username}。
%cd /content/{destination_repo_username}
检查是否一切正常!
!git pull
如果克隆后没有对远程 git repo 进行任何更改,则应显示以下输出:
Already up to date.
类似地检查分阶段/非分阶段更改的状态。
!git status
它应该显示这个,并选择默认分支:
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree clean
检查您之前在 repo 上所做的提交:
!git log -n 4
输出带有日志的 Git 提交 ID:
commit 18ccf27c8b2d92b560e6eeab2629ba0c6ea422a5 (HEAD -> main, origin/main, origin/HEAD)
Author: Farhan Hai Khan <njrfarhandasilva10@gmail.com>
Date: Mon May 31 00:12:14 2021 +0530
Create README.md
commit bd6ee6d4347eca0e3676e88824c8e1118cfbff6b
Author: khanfarhan10 <njrfarhandasilva10@gmail.com>
Date: Sun May 30 18:40:16 2021 +0000
Add Zip COVID
commit 8a3a12863a866c9d388cbc041a26d49aedfa4245
Author: khanfarhan10 <njrfarhandasilva10@gmail.com>
Date: Sun May 30 18:03:46 2021 +0000
Add COVID Data
commit 6a16dc7584ba0d800eede70a217d534a24614cad
Author: khanfarhan10 <njrfarhandasilva10@gmail.com>
Date: Sun May 30 16:04:20 2021 +0000
Removed sample_data using colab (testing)
从本地 repo 目录进行更改。
这些可能包括编辑、删除、编辑。
from google.colab import drive
drive.mount('/content/gdrive')
import shutil
# For a folder:
shutil.copytree(src_folder,des_folder)
# For a file:
shutil.copy(src_file,des_file)
# Create a ZipFile
shutil.make_archive(archive_name, 'zip', directory_to_zip)
告诉 Git 你是谁?
!git config --global user.name "{your_username}"
!git config --global user.email "{your_email_id}"
!git config --global user.password "{your_password}"
检查远程 url 是否设置和配置正确:
!git remote -v
如果配置正确,它应该输出以下内容:
origin https://{your_username}:{your_password}@github.com/{destination_repo_username}/{destination_repo_projectname}.git (fetch)
origin https://{your_username}:{your_password}@github.com/{destination_repo_username}/{destination_repo_projectname}.git (push)
你知道该怎么做。
!git add .
!git commit -m "{Message}"
!git push
享受吧!
【讨论】:
https://stackoverflow.com/a/53094151/3924118 解决方案对我不起作用,因为表达式 {user} 没有被转换为实际用户名(我收到 400 错误请求),所以我将该解决方案稍微更改为以下解决方案。
from getpass import getpass
import os
os.environ['USER'] = input('Enter the username of your Github account: ')
os.environ['PASSWORD'] = getpass('Enter the password of your Github account: ')
os.environ['REPOSITORY'] = input('Enter the name of the Github repository: ')
os.environ['GITHUB_AUTH'] = os.environ['USER'] + ':' + os.environ['PASSWORD']
!rm -rf $REPOSITORY # To remove the previous clone of the Github repository
!git clone https://$GITHUB_AUTH@github.com/$USER/$REPOSITORY.git
os.environ['USER'] = os.environ['PASSWORD'] = os.environ['REPOSITORY'] = os.environ['GITHUB_AUTH'] = ""
如果您能够克隆your-repo,您应该不会在此命令的输出中看到任何密码。 如果出现错误,密码可能会显示在输出中,因此请确保在此命令失败时不要共享笔记本。
【讨论】:
我在这里尝试了一些方法,它们都运行良好,但我遇到的一个问题是,在笔记本单元格中处理所有 git 命令和其他相关命令变得很困难,例如使用 DVC 进行版本控制。所以,我转向了这个不错的解决方案,Kora。它是一个可以在 colab 中运行的终端仿真器。这提供了与本地机器中的终端非常相似的易用性。笔记本仍然存在,我们可以像往常一样编辑文件和单元格。由于此控制台是临时的,因此不会公开任何信息。 GitHub登录等命令可以照常运行。
科拉:https://pypi.org/project/kora/
用法:
!pip install kora
from kora import console
console.start()
【讨论】:
我终于振作起来,为此编写了一个 python 包。
pip install clmutils # colab-misc-utils
在 /content/drive/MyDrive(如果谷歌驱动器安装到驱动器)或 /content/drive/.env 中创建一个 dotenv 或 .env
# for git
user_email = "your-email"
user_name = "your-github-name"
gh_key = "-----BEGIN EC PRIVATE KEY-----
...............................................................9
your github private key........................................J
..................................==
-----END EC PRIVATE KEY-----
"
在 Colab 单元中
from clmutils import setup_git, Settings
config = Settings()
setup_git(
user_name=config.user_name,
user_email=config.user_email,
priv_key=config.gh_key
)
然后,您就可以在家里或工作的自己可爱的电脑上做所有git cloen、修改代码、git push 的事情了。
clmutils 还有一个名为setup_ssh_tunnel 的函数,用于设置到 Colab 的反向 ssh 隧道。它还从 .env 文件中读取各种密钥、用户名、主机名。这有点涉及。但是,如果您知道如何手动设置到 Colab 的反向 ssh 隧道,那么您就可以毫无问题地弄清楚它们的用途。详细信息可在 github repo (google clmutils pypi) 上找到。
【讨论】:
使用以下方式安装驱动器:
from google.colab import drive
drive.mount('/content/drive/')
然后:
%cd /content/drive/
克隆驱动器中的存储库
!git clone <github repo url>
从 repo 访问其他文件(例如:helper.py 是 repo 中的另一个文件):
import imp
helper = imp.new_module('helper')
exec(open("drive/path/to/helper.py").read(), helper.__dict__)
【讨论】:
如果你想分享你的 repo 和 colab,这很有效。如果您有多个存储库,也可以使用。把它扔进一个牢房里。
import ipywidgets as widgets
from IPython.display import display
import subprocess
class credentials_input():
def __init__(self, repo_name):
self.repo_name = repo_name
self.username = widgets.Text(description='Username', value='')
self.pwd = widgets.Password(description = 'Password', placeholder='password here')
self.username.on_submit(self.handle_submit_username)
self.pwd.on_submit(self.handle_submit_pwd)
display(self.username)
def handle_submit_username(self, text):
display(self.pwd)
return
def handle_submit_pwd(self, text):
cmd = f'git clone https://{self.username.value}:{self.pwd.value}@{self.repo_name}'
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
print(output, error)
self.username.value, self.pwd.value = '', ''
get_creds = credentials_input('github.com/username/reponame.git')
get_creds
【讨论】:
另一个基于@Marafon Thiago 回答的解决方案:
注意:在带有特殊字符的密码中,使用字符各自的encoding。
例如 passwd = '@123' 你应该输入 :passwd = '%40123'
from getpass import getpass
user = getpass('BitBucket user')
password = getpass('BitBucket password')
!git init
!git clone https://{user}:{password}@bitbucket.org/aqtechengenharia/aqtlibpy.git
【讨论】: