如何使用Python自动化Git推送流程?

4

我正在尝试使用Python自动化git push进程。

我已经成功自动化了除了在git push命令之后输入用户名和密码之外的所有内容。

这是我目前的代码:

import subprocess
import sys

add: str = sys.argv[1]
commit: str = sys.argv[2]
branch: str = sys.argv[3]


def run_command(command: str):
    print(command)
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    print(str(process.args))
    if command.startswith("git push"):
        output, error = process.communicate()
    else:
        output, error = process.communicate()
    try:
        output = bytes(output).decode()
        error = bytes(error).decode()
        if not output:
            print("output: " + output)
        print("error: " + error)
    except TypeError:
        print()


def main():
    global add
    global commit
    global branch
    if add == "" or add == " ":
        add = "."
    if branch == "":
        branch = "master"
    print("add: '" + add + "' commit: '" + commit + "' branch: '" + branch + "'")

    command = "git add " + add
    run_command(command)

    commit = commit.replace(" ", "''")
    command = 'git commit -m "' + commit + '"'
    run_command(command)

    command = "git push origin " + branch
    run_command(command)


if __name__ == '__main__':
    main()

有没有办法将信息发送到命令中?

也许可以在Python中使用一个GIT模块!看一下Python Git Module experiences?,里面有一些有趣的答案! - F. Hauri - Give Up GitHub
3个回答

2
如果可能的话,使用凭据助手来缓存与远程URL相关联的信息(凭据)。请查看git凭证部分和“Git工具-凭证存储”。
git config --global credential.helper

那样,您就不必输入那些信息了。

我应该在哪里写这个? 我刚在终端中运行了它,但它没有做什么... - TheZadok42
@TheZadok42 如果没有返回任何内容,那就意味着没有设置凭证助手。你的操作系统是什么?Git 版本是多少?根据这些信息,你可以设置一个凭证助手。 - VonC
我正在使用Linux(Arch with i3wm)和git(版本2.17.0)。 - TheZadok42
@TheZadok42 然后使用libsecret,如我在 https://dev59.com/4WYr5IYBdhLWcg3wy9KA#13386417 和 https://dev59.com/WVoV5IYBdhLWcg3wLsT5#40312117 中所记录的。确保你的Python程序将与用于该git配置的相同用户一起运行。 - VonC
我输入命令后,还需要进行其他设置吗? - TheZadok42
@TheZadok42 首先,请查看 https://dev59.com/WVoV5IYBdhLWcg3wLsT5#40312117 以获取更多详细信息。其次,从任何文件夹中在命令行中执行以下操作:git ls-remote /url/of/remote/repo:如果需要身份验证,则会询问您的用户名/密码并将其缓存。然后,您就可以继续进行Python程序了。 - VonC

1

这是我解决问题的方法:

# make sure to cd into the git repo foler

import subprocess
import sys
import os


msg = input('Type the commit message (+ ENTER):') 
repo_directory = os.getcwd()

subprocess.run(["git", "add", "."], cwd=repo_directory)
# commit file
subprocess.run(["git", "commit", "-m", msg], cwd=repo_directory)
# push
subprocess.run(["git", "push"], cwd=repo_directory)  

0

GitPython 库

from git import repo

repo = Repo('PATH/directory')
repo.git.add('file.txt')
repo.index.commit('commit message')
origin =
repo.remote(name='origin')
origin.push()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接