如何使用python自动化git推送过程?

ttcibm8c  于 2022-12-17  发布在  Git
关注(0)|答案(2)|浏览(145)

我正在尝试使用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()

有没有办法把信息传给指挥部?

jv4diomz

jv4diomz1#

如果可能,使用凭据帮助器来缓存该信息(与远程URL关联的凭据)。
检查gitcredential section和“Git Tools - Credential Storage“。

git config --global credential.helper

这样,您就完全不必输入这些信息。

ve7v8dk2

ve7v8dk22#

我是这样解决的:

# 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)

相关问题