Pythonはグーグルのプロトコルファイルに対して.protoファイルの生成と処理(pythonコマンド、検索、置換)

2717 ワード

作業中、単純で秩序があるが頻度が高いという問題に対して、ツールとしていわゆるバッチ処理を行うことで、高い作業効率を向上させることができ、以下はプロトコルファイルの生成と処理である.ここで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 

ここ、入り口を見て
まずosを使います.System()はコマンドを実行する、生成プログラムが利用可能である.pb.h和.pb.ccファイル(注:ここでは生成されたC++コードで使用可能なファイルタイプ)
生成後、Googleのバージョン番号が私の使用時と一致しないという問題が発生しました.
#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は鋭いです)
2つの変更方法を追加します.
 
  
/**
*  @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は1つです.exeファイル、使用時にコンピュータの環境変数を構成します