在工作中難免有些重復性極高的代碼需要生成,便用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")
如有建議和指正,歡迎評論留言討論。