Skip to main content
 首页 » 编程设计

python之使用 GitPython 从远程存储库中克隆所有分支的存储库

2025年05月04日6飞鱼

我正在尝试为我的用户制作一个小程序,用于 git 和其他程序的基本操作。我在克隆私有(private)远程存储库时遇到了很多问题。

我有以下配置: Python 3.4 window GitPython 在远程服务器上建立 Ssh 连接。

这是我的代码:

print(blue + "Where to clone repos ?") 
path_repo = input(cyan + "> " + green) 
try: 
    assert os.path.exists(path_repo) 
except AssertionError: 
    print(red + "Path does not exist") 
continue 
print(blue + "Name of Repos :") 
name_repo = input(cyan + "> " + green) 
remote_path = "git@dev01:/home/git/repos/{0}.git".format(name_repo) 
local_path = "{0}/{1}".format(path_repo, name_repo) 
# Repo.clone_from(remote_path, local_path) 
repo = Repo.clone_from(remote_path, local_path) 
#print(repo.git.fetch()) 
#print(repo.git.pull()) 
#print(repo.git.status()) 

这不会引发错误,但脚本会在最后停止并阻塞终端(给我没有 >>> 的无限空行)

运行之后,如果我进入 Git Bash 并输入 git status 他似乎没有创建分支,只有 init。因此,我添加了代码的最后 3 行以查看更改的内容,但没有任何更改。

如果在 Git Bash 中我输入 git pull,他会拉好 master 分支...

请问有人能解决我的问题吗?

我哪里出错了?

谢谢

请您参考如下方法:

您描述的代码和方法存在很多问题...

一个

首先,你有

continue 

写在您的代码中间...所以我假设您提供的代码处于某个循环中。循环中无条件 continue 之后的所有代码都是死代码 - 它永远不会被执行。

因此,您似乎从未真正克隆过任何东西...

两个

要查看存储库中的所有分支,请使用类似 git branch -va 的东西。恐怕 git status 不是为此而生的。

三个

由于您似乎已经以某种方式初始化了存储库,因此您将无法克隆到同一位置 - 因为克隆会创建存储库。

四个

此外,检查目录是否存在也没有意义 - 因为如果目录不存在,git clone 会创建目录。


总而言之,试试下面这个简单的代码。由于存储库已经存在,我已经注释掉了可能导致错误的行。

print(blue + "Where to clone repo?") 
path_repo = input(cyan + "> " + green) 
print(blue + "Name of repo:") 
name_repo = input(cyan + "> " + green) 
remote_path = "git@dev01:/home/git/repos/{0}.git".format(name_repo) 
local_path = "{0}/{1}".format(path_repo, name_repo) 
#repo = Repo.clone_from(remote_path, local_path) 
repo = Repo(local_path) 
info = repo.remote('origin').fetch() 
if not info: 
    print('no fetch information') 
for i in info: 
    if i.note: 
        print('fetched, note is: ' + i.note.strip()) 
    else: 
        print('fetched, no note')