使用 Python 構建個人代碼生成器


在工作中難免有些重復性極高的代碼需要生成,便用Python 寫了很簡易的一個代碼生成器,快速生成重復代碼,將時間用到更值得學習的地方。
代碼如下:

#! /usr/bin/env python
#coding=utf-8
import os
from string import Template


#
# 代碼生成器所需的數據配置字典
# 在需要生成地方使用 ${key-name} 配置,如下:
# class C${Class_Name}
#
config_dict = {
    'CLASSNAME' : 'DEFAULT',
    'Class_Name' : 'Default',
    'En_name' : 'mystruct',
    'Type' : 'int',
    'Name' : 'value'
}

def gen(tmpl, out):
        if not os.path.exists(out):  # 如不存在目標目錄則創建
            os.makedirs(out)
        files = os.listdir(tmpl)  # 獲取文件夾中文件和目錄列表
        for f in files:
            if os.path.isdir(tmpl + '/' + f):  # 判斷是否是文件夾
                gen( tmpl + '/' + f, out + '/' + f)  # 遞歸調用本函數
            else:
                gen_one_file(tmpl + '/' + f, get_out_filename(f,out), config_dict)  # 拷貝文件


def gen_one_file(tmpl, target, config_dict):
        filePath = target
        class_file = open(filePath, 'w')

        mycode = []

        # 加載模板文件
        template_file = open(tmpl, 'r')
        tmpl = Template(template_file.read())

        # 模板替換
        mycode.append(tmpl.substitute(config_dict))

        # 將代碼寫入文件
        class_file.writelines(mycode)
        class_file.close()

        print('ok')

def get_out_filename(temp_name, out_dir):
    # 生成文件跟模板名相同
    return out_dir + '/' + temp_name

if __name__ == '__main__':
    gen("templ", "out")

如有建議和指正,歡迎評論留言討論。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM