Python 对谷歌协议文件 .proto 文件的生成与处理 (python 命令、查找、替换)

工作中,对于简单有序但是频率出现较高的问题,做一个工具对其进行所谓的批处理是能够提升很高的工作效率的,下面是对协议文件的生成 与 处理。
这里我是用了python做了一个脚本,生成可使用的程序使用文件 以及 对文件的响应处理


__author__ = 'xxxxxx'
import os
import codecs
import sys
# import this

class Tools:
    def __init__(self, path):
        self.path = path

    def _replace_file(self, path, old, new):
        fp = codecs.open(path, 'r', 'utf-8')
        data = fp.read()
        data = data.replace(old, new)
        fp.close()
        fp = codecs.open(path, 'w', 'utf-8')
        fp.write(data)
        fp.close()

    def _replace_all_file(self, path, re_file_type, old, new):
        for(path, dirs, files) in os.walk(path):
            for filename in files:
                print filename
                ext = os.path.splitext(filename)[1]
                print ext
                if (ext == re_file_type):
                    self._replace_file(filename, old, new)
                    print "over"


if __name__ == '__main__':
    cur_dir = os.path.dirname(os.path.realpath(__file__))
    os.system("protoc OGGameLogicProtocol.proto --cpp_out=./")
    os.system("protoc OGLordBasicDataPB.proto --cpp_out=./")

    builder = Tools(cur_dir)
    builder._replace_all_file(cur_dir, ".h", "< 2003000", "< 2004000")
    builder._replace_all_file(cur_dir, ".h", "2003000 <", "2004001 <")

这里,看一下入口

首先,我是用 os.system()执行命令,生成程序可用的 .pb.h 和 .pb.cc 文件 (注:这里是生成的 C++代码可用的文件类型)

生成后,使用时发现如下问题:谷歌的版本号跟我使用时用的不一致

#if GOOGLE_PROTOBUF_VERSION < 2003000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please update
#error your headers.
#endif
#if 2003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please
#error regenerate this file with a newer version of protoc.
#endif
需要对版本号进行修改,由于我生成的可能是很多个文件,所以手动修改起来比较繁琐,影响心情,所以,python代码实现修改(python很犀利)


添加两个修改方法:

/**
*  @brief  遍历指定路径下的文件
*
*  @param path:遍历文件的路径
*  @param re_file_type:需要处理的文件类型  ".h"  ".txt"  ".cc"  ".cpp"  etc.
*  @param old:需要替换的原来的内容
*  @param new:需要替换的现在的内容
*/
def _replace_all_file(self, path, re_file_type, old, new) :

/**
*  @brief  用于将遍历到的文件进行查找替换
*
*  @param path:遍历文件的路径
*  @param old:需要替换的原来的内容
*  @param new:需要替换的现在的内容
*/
def _replace_file(self, path, old, new) : 

注:protoc 是一个.exe文件,使用时配置一下电脑的环境变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值