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 = [
    '[email protected]:project/mengxixing-h5.git',
    '[email protected]:project/waterinbrainopendomain.git',
    '[email protected]: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)


猜你喜欢

转载自blog.csdn.net/KiTok/article/details/134741120
今日推荐