目标
完成一个python脚本,实现指定名字后,自动生成.c和.h的模板。例如:
/** * @file epc.c * @author 陈维 * @version V01 * @date 2017.01.11 * @brief epc芯片驱动 * @note * * @attention COYPRIGHT INMOTION ROBOT */
代码
# ctemplate.py import sys import datetime class ctemplate: __fileName = ' ' __sourceName = ' ' __headerName = ' ' __time = datetime.datetime.now().strftime('%Y.%m.%d') __fileComments = {'@attention':'COPYRIGHT WEYNE', '@note':' ', '@brief':' ', '@date':__time, '@version':'V01', '@author':'Weyne Chen', '@file':" ", } __CommentsOrder = ('@file','@author','@version','@date','@brief','@note','@attention') def __init__(self,s): self.__fileName = s self.__sourceName = s + ".c" self.__headerName = s + '.h' def generateCommentsAtTop(self,name): self.__fileComments['@file'] = name comments = ('/** ') #find max length of string maxLen = 0 for s in self.__CommentsOrder: if(len(s) > maxLen): maxLen = len(s) for k in self.__CommentsOrder: alignSpaceAmount = maxLen - len(k) + 4 alignSpace = alignSpaceAmount * ' ' comments += ('* '+ k + alignSpace + self.__fileComments[k] + ' ') comments += ('**/ ') return comments def generateCommentsInTheEnd(self): return ("/********************* (C) COPYRIGHT WEYNE CHEN *******END OF FILE ********/ ") def createSource(self): fh = open(self.__sourceName,mode = 'w',encoding='utf-8') cm = self.generateCommentsAtTop(self.__sourceName) cm += ("#include "%s" " %self.__headerName) cm += (" "*5) cm += self.generateCommentsInTheEnd() fh.write(cm) fh.close() def createHeader(self): fh = open(self.__headerName,mode = 'w',encoding='utf-8') cm = self.generateCommentsAtTop(self.__headerName) cm += "#ifndef __%s_H " %self.__fileName.upper() cm += "#define __%s_H " %self.__fileName.upper() cm += (" "*5) cm += "#endif " cm += self.generateCommentsInTheEnd() fh.write(cm) fh.close() def createTemplatePairs(self): self.createSource() self.createHeader() if __name__ == '__main__': if len(sys.argv) != 2: sys.stderr.write("please input corret parameter") else: s = sys.argv[1] ct = ctemplate(s) ct.createTemplatePairs()
在CMD中执行 python ctemplate.py test
之后,会生成test.c和test.h文件,并已经添加部分描述内容。效果如下:
test.c
/** * @file test.c * @author Weyne Chen * @version V01 * @date 2017.01.19 * @brief * @note * @attention COPYRIGHT WEYNE **/ #include "test.h" /********************* (C) COPYRIGHT WEYNE CHEN *******END OF FILE ********/
test.h
/** * @file test.h * @author Weyne Chen * @version V01 * @date 2017.01.19 * @brief * @note * @attention COPYRIGHT WEYNE **/ #ifndef __TEST_H #define __TEST_H #endif /********************* (C) COPYRIGHT WEYNE CHEN *******END OF FILE ********/
总结
需要注意python字典在迭代器输出时,不是按输入顺序输出的。因为其存储过程实际是散列的,所以输出的顺序是不定的。若是想要顺序输出,只能使用list或者给dict增加一个tuple,并将key值存储到tuple中。