python 學習之批處理protobuf轉pb

創建一個python文件transProtoCmd.py(Mac機)
程序入口

import os
import getpass

if __name__ == '__main__':
    username = getpass.getuser()
    os.chdir('/Users/' + username + '/Documents/')
    print os.getcwd()
    handleFile()

os.getcwd()方法獲取當前的目錄
getpass.getuser() 該函數返回登陸的用戶名,不需要參數
os.chdir(‘directoryName’)改變當前工作目錄到指定的路徑

先來看獲取要進行轉化的.proto文件有哪些

def getFileInfo():
    t = {}
    # get protobuf srcPath directory from svn download
    # /User/xxx/Documents/public/new_protocol/
    dir = os.getcwd()+os.sep+"public/new_protocol/" 
    # get all .proto file
    for filename in os.listdir(dir):
        curfile = dir + filename
        if os.path.isfile(curfile):
            houzhui = curfile[curfile.rfind('.'):]
            if houzhui == '.proto':
                file = filename[:filename.rfind('.')]
                t[file] = curfile
    # eg. t['aaa'] = /User/xxx/Documents/public/new_protocol/aaa.proto
    return t    

假設要將這些文件轉爲.pb文件,之前用的方法一直都是將.proto文件手動複製到安裝了protobuf的擁有protoc命令文件的同級目錄下,然後再單個執行命令protoc –descriptor_set_out xxx.pb xxx.proto,生成的.pb文件當然也是在此命令的同級目錄,再複製到項目工程中…
現在要批量處理,本來是想通過protoc –descriptor_set_out (想轉成的文件的全路徑名)(準備轉的全路徑名),想一鍵自動生成,發現一直沒成功,那隻好代碼中實現先將這些.proto原文件(比如直接從svn下載下來的)拷貝到protoc命令的同級目錄,對.proto文件循環遍歷生成.pb,然後將這些.pb拷貝到項目工程目錄。


def handleFile():
    t = getFileInfo()

    username = getpass.getuser()
    os.chdir('/Users/' + username + '/protobuf/src/')

    table = {}
    for key in t.keys():
        filename = key
        pathname = t[key]

        name    = filename + '.proto'
        strpath = '/Users/ximi/Documents/client/MyProj/protobuff/' + filename + '.proto'
        f1 = open(pathname, 'r+')
        f2 = open(name, 'w+')
        f3 = open(strpath, 'w+')

        for s in f1.readlines():
            f2.write(s)
            f3.write(s)

        f1.close()
        f2.close()
        f3.close()

        destname = filename + '.pb '
        srcname  = filename + '.proto'
        cmd = "protoc --descriptor_set_out " + destname + srcname
        os.system(cmd)

        pathname1 = os.getcwd() + '/' + filename + '.pb'
        table[filename] = pathname1

    username = getpass.getuser()
    # destpath = '/Users/' + username + '/Documents/work2/'
    destpath = "/Users/ximi/Documents/client/MyProj/src/app/network/proto/" 
    for key in table.keys():
        filename = key
        pathname = table[key]

        name = destpath + filename + '.pb'
        f1 = open(pathname, 'r+')
        f2 = open(name, 'w+')

        for s in f1.readlines():
            f2.write(s)

        f1.close()
        f2.close()

這樣就將/User/ximi/Documents/public/new_protocol/ 文件下的.proto文件通過命令protoc轉爲.pb文件,全部自動拷貝到我的項目工程目錄/Users/ximi/Documents/client/MyProj/src/app/network/proto/ 裏面,並將該.proto文件也拷貝到項目目錄/Users/ximi/Documents/client/MyProj/protobuff/ 裏面。

發佈了29 篇原創文章 · 獲贊 5 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章