您的位置:首页 > 编程语言 > Python开发

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

2015-11-20 16:08 701 查看
工作中,对于简单有序但是频率出现较高的问题,做一个工具对其进行所谓的批处理是能够提升很高的工作效率的,下面是对协议文件的生成 与 处理。

这里我是用了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文件,使用时配置一下电脑的环境变量
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: