首页 > 编程语言 >同步proto的python脚本

同步proto的python脚本

时间:2022-11-27 15:33:34浏览次数:43  
标签:同步 proto python self file path dir

import os
import sys
import subprocess
import shutil


"""
    功能:
        1. 拷贝python的proto到go的对应目录之下
        2. 生成python的源码 - import .
        3. 生成go的源码
"""

class cd:
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)


def replace_file(file_name):
    new_file_name = f"{file_name}-bak"
    modify_times = 0   # 统计修改次数
    f1 = open(file_name,'r',encoding='utf-8')    # 以“r”(只读)模式打开旧文件
    f2 = open(new_file_name,'w',encoding='utf-8')  # 以“w”(写)模式打开或创建新文件(写模式下,文件存在则重写文件,文件不存在则创建文件)
    for lines in f1: # 循环读
        if lines.startswith("import") and not lines.startswith("import grpc"):
            lines = f"from . {lines}"
            modify_times += 1  # 每修改一次就自增一次
        f2.write(lines) # 将修改后的内容后的内容写入新文件
    print('文件修改的次数:',modify_times) # 9
    f1.close()  # 关闭文件f1
    f2.close()  # 关闭文件f2(同时打开多个文件时,先打开的先关闭,后打开的后关闭)
    os.replace(new_file_name,file_name) # 修改(替换)文件名


def proto_file_list(path):
    flist = []
    lsdir = os.listdir(path)
    dirs = [i for i in lsdir if os.path.isdir(os.path.join(path, i))]
    if dirs:
        for i in dirs:
            proto_file_list(os.path.join(path, i))
    files = [i for i in lsdir if os.path.isfile(os.path.join(path, i))]
    for file in files:
        if file.endswith(".proto"):
            flist.append(file)
    return flist


def copy_from_py_to_go(src_dir, dst_dir):
    proto_files = proto_file_list(src_dir)
    for proto_file in proto_files:
        try:
            shutil.copy(f"{src_dir}/{proto_file}", dst_dir)
        except IOError as e:
            print("Unable to copy file. %s" % e)
        except:
            print("Unexpected error:", sys.exc_info())


def generated_pyfile_list(path):
    flist = []
    lsdir = os.listdir(path)
    dirs = [i for i in lsdir if os.path.isdir(os.path.join(path, i))]
    if dirs:
        for i in dirs:
            proto_file_list(os.path.join(path, i))
    files = [i for i in lsdir if os.path.isfile(os.path.join(path, i))]
    for file in files:
        if file.endswith(".py"):
            flist.append(file)
    return flist


class ProtoGenerator:
    def __init__(self, python_dir, go_dir):
        self.python_dir = python_dir
        self.go_dir = go_dir

    def generate(self):
        with cd(self.python_dir):
            files = proto_file_list(self.python_dir)
            subprocess.call("workon mxshop_srv", shell=True)
            for file in files:
                command = f"python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. {file}"
                subprocess.call(command)

            #查询生成的py文件并添加上 from .
            py_files = generated_pyfile_list(self.python_dir)
            for file_name in py_files:
                replace_file(file_name)
            print(py_files)

        with cd(self.go_dir):
            files = proto_file_list(self.go_dir)
            for file in files:
                command = f"protoc -I . {file} --go_out=plugins=grpc:."
                subprocess.call(command)


class PyProtoGenerator:
    def __init__(self, python_dir):
        self.python_dir = python_dir

    def generate(self):
        with cd(self.python_dir):
            files = proto_file_list(self.python_dir)
            subprocess.call("workon mxshop_srv", shell=True)
            for file in files:
                command = f"python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. {file}"
                subprocess.call(command)

            #查询生成的py文件并添加上 from .
            py_files = generated_pyfile_list(self.python_dir)
            for file_name in py_files:
                replace_file(file_name)
            print(py_files)


if __name__ == "__main__":
    #goods的proto生成
    # python_dir = "C:\\Users\\Administrator\\PycharmProjects\\mxshop_srvs\\userop_srv\\proto"
    # go_dir = "D:\\python微服务\\projects\\mxshop-api\\userop-web\\proto"
    # #
    # # #将py目录下的文件夹拷贝到go目录下
    # copy_from_py_to_go(python_dir, go_dir)
    # #
    # # #生成对应的py源码和go源码
    # gen = ProtoGenerator(python_dir, go_dir)
    # gen.generate()

    py_gen = PyProtoGenerator("C:\\Users\\Administrator\\PycharmProjects\\mxshop_srvs\\inventory_srv\\proto")
    py_gen.generate()

  

标签:同步,proto,python,self,file,path,dir
From: https://www.cnblogs.com/wlike/p/16929784.html

相关文章

  • centeros7升级python2.5.7到python3.5.2
    centos7python2.7.5升级到3.5.2下载python3.5.2wgethttps://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz安装解压:tar-zxvfPython-3.5.2.tgz进入解压目录:cdPyt......
  • python数学库01
    importmathimportmatplotlib.pyplotasplt_name_='__main__'if_name_=="__main__":x=[float(i)/100foriinrange(1,300)]y=[math.log(i......
  • 力扣162(java&python)-寻找峰值(中等)
    题目:峰值元素是指其值严格大于左右相邻值的元素。给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可......
  • Python9 字符串
    字符串简介和驻留机制基本数据类型、不可变的字符序列驻留机制:有个驻留池留着相同的字符串,如果内容相同,就不会再去开辟空间存储了,意思是内容相同的字符串占一个位你可......
  • python-数学库安装
    python库的安装方法1pycharm==>设置==>项目:项目名==>python解释器==>+(按钮)==搜索库安装Pycharm安装:优点:每一个项目单独加载所需要的库,......
  • python 列表排序方法
    常见的列表排序方法参考:https://blog.csdn.net/m0_69265664/article/details/125703164iterable.sort()参考:https://blog.csdn.net/rhx_qiuzhi/article/details/1193025......
  • Git同步操作
    同步github数据首先要进入仓库文件夹新建仓库文件夹要初始化或将远程仓库clone下来gitinit或gitclonehttps://github.com/用户名称/仓库名称.git新建仓库文件夹连......
  • python算数运算符
    Python支持的所有基本算术运算符; 加法运算符:示例:1a=102b=963sum1=a+b45x=3.146y=5.347sum2=x+y89print("sum1=%d,sum2=%.2f"%......
  • python-re 正则模块
    \W+:匹配一个或多个非字母进行切割,匹配到的非字母不缓存;(\W+):匹配一个或多个非字母进行切割,匹配到的非字母全部缓存;(\W)+:匹配一个或多个非字母进行切割,匹配到的非字母缓存......
  • Python基于pip实现离线打包
    转载自 https://www.zhangshengrong.com/p/x7XRM7byNz/新公司是内网环境,无法使用pip安装第三方资源库,在网上搜下,可以直接使用pip打包本机所安装的第三方资源库,打包成whl......