Python批量Git Pull,对文件夹批量进行Pull操作

效果展示

在这里插入图片描述

说明

  1. 本来是想写的完善一些,但由于是自用,所以写出来后发现已经解决了自己的问题,所有 2和3功能没有写。

  2. 执行的话,需要 cmd 之后 直接 Python BatchGitPull.py 运行下面代码即可。

  3. 里面同时涉及到其他Pyhon知识点(写给自己的,因为自己老记不住):
    1. 输入任意键退出控制台
    2. 控制台输出不同颜色
    3. 获取命令执行后的返回结果
    4. 根据不同的输入执行不同的代码
    5. 获取用户管理员权限,从而刷新系统DNS
    6. …

  4. 注意:is_admin 这个访问是来判断是否有管理员权限的,如果担心代码有问题,可以去掉管理员权限的相关代码。我是因为个人情况,不加的话,无法进行系统DNS的刷新,导致有时候梯子换了频道后,还是Pull不下来,所以出此下策。

具体代码

#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import time
import ctypes
import sys
import subprocess
import colorama
from colorama import Fore, Style


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


dir_root = 'N:/Program Files/sd-webui-aki-v4.4/ComfyUI/ComfyUI/custom_nodes'


def PrintError(log):
    print(Fore.RED + log + Style.RESET_ALL)  # 红色


def PrintSuccess(log):
    print(Fore.GREEN + log + Style.RESET_ALL)  # 绿色


def BatchPull():
    dir_route = dir_root
    if os.path.exists(dir_route) == False:
        PrintError("没有这个文件夹 " + dir_root)
        return
    # 切换到test目录
    os.chdir(dir_route)
    current_directory = os.getcwd()
    dirs = os.listdir()
    # 定义git命令
    command = 'git pull'  # origin master'
    netCommand = 'ipconfig/flushdns'
    index = 0
    error_list = {}
    for code_dir in dirs:
        index += 1
        # 拼接路径(当前目录+代码目录)
        result = subprocess.run(
            netCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)

        # 获取标准输出

        # 获取标准错误输出(如果有)
        if result.returncode != 0:
            PrintError("网络错误输出:" + result.stderr)
        else:
            print("刷新网络成功!")  # + result.stdout)
        

        full_path = os.path.join(current_directory, code_dir)
        if os.path.isdir(full_path) == False:
            print("跳过:不是文件夹 " + full_path)
            continue
        os.chdir(full_path)
        print(str(index) + " : 进行 Pull " + code_dir)
       
        result = subprocess.run(
            command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)

        waitTimer = 2
        # 获取标准错误输出(如果有)
        # 检查returncode判断命令是否执行成功
        if result.returncode != 0:
            waitTimer *= 2
            PrintError("错误输出:" + result.stderr)
            error_list[index] = code_dir
        else:
            PrintSuccess("完成输出:" + result.stdout)
       
        time.sleep(waitTimer)
        # print(code_dir + " Pull完毕! " + full_path + '\n')
        os.chdir(dir_route)

    if len(error_list) > 0:
        for err in error_list:
            PrintError("未完成列表:" + str(err) + " : " + error_list[err])
    else:
        PrintSuccess("完美!全部更新成功!!")

    input("按回车键退出...")


project_addr = [
    'git@gitlab.com:project/mengxixing-h5.git',
    'git@gitlab.com:project/waterinbrainopendomain.git',
    'git@gitlab.com:project/waterinbrain.git'
]


def BatchClone():
    os.mkdir('E:/code')
    os.chdir('E:/code')
    command = 'git clone '
    for i in project_addr:
        os.popen(command + str(i))
        time.sleep(1)
        print(i + " Clone完毕!")

    print('当前项目组已全部拉取完毕')


# BatchPull()

if is_admin():
    # 初始化colorama
    colorama.init()

    #PrintSuccess("测试")
    user_input = input("将对 \" " + dir_root + " \" 文件夹下所有子文件执行批量Git操作,请确定路径正确。\n\n" +
                       "请选择操作方式: \n1. 按1键 则全部执行Pull,获取最新代码。\n2. 按2键 则只执行Pull失败的库 " +
                       "\n3. 按3键 暂时未开发\n \n \n 注意:\n1. 只有当1键执行后才会有Pull错误数据,这时候2键才有效果\n2. 按键后,再按回车键来确定\n" +
                       "___________________________________________\n")

    if user_input == "1":

        BatchPull()
    elif user_input == "2":
        print("执行了B操作")
    elif user_input == "3":
        input("暂未任何操作,按回车键退出...")
    else:
        input("无效输入,按回车键退出...")

else:
    ctypes.windll.shell32.ShellExecuteW(
        None, "runas", sys.executable, " ".join(sys.argv), None, 1)


  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以通过调用git命令来操作git,可以使用subprocess模块来执行git命令。以下是一些常用的git操作: 1. 克隆仓库: 可以使用以下代码来克隆一个git仓库: ```python import subprocess subprocess.run(['git', 'clone', 'https://github.com/username/repo.git']) ``` 2. 拉取代码: 可以使用以下代码来拉取代码: ```python import subprocess subprocess.run(['git', 'pull']) ``` 3. 提交代码: 可以使用以下代码来提交代码: ```python import subprocess subprocess.run(['git', 'add', '.']) subprocess.run(['git', 'commit', '-m', 'commit message']) subprocess.run(['git', 'push']) ``` 上述代码会将所有更改添加到暂存区,提交到本地仓库并将更改推送到远程仓库。 4. 创建分支: 可以使用以下代码来创建一个新的git分支: ```python import subprocess subprocess.run(['git', 'checkout', '-b', 'new-branch']) ``` 上述代码会创建一个名为"new-branch"的新分支并将其切换到当前分支。 5. 切换分支: 可以使用以下代码来切换到一个已经存在的分支: ```python import subprocess subprocess.run(['git', 'checkout', 'branch-name']) ``` 上述代码会将当前分支切换到名为"branch-name"的分支。 6. 合并分支: 可以使用以下代码来合并两个分支: ```python import subprocess subprocess.run(['git', 'checkout', 'target-branch']) subprocess.run(['git', 'merge', 'source-branch']) ``` 上述代码会将名为"source-branch"的分支合并到名为"target-branch"的分支中。 注意:在实际使用中,应该检查命令的返回值来确保操作成功。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值