Python使用模板自动生成代码

整体思想:

      完全按照自己的想法来写的,首先写模板文件,然后打开模板文件,对模板进行字符串格式化处理,最后再将格式化后的字符串保存到新的文件里面。如有更好的想法,欢迎交流。

将相似度很高的代码写模板文件(widget_template.txt):

# -*- coding: UTF-8 -*-
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name:        auto
# Purpose:
#
# Author:      Yang
#
# Created:     13/08/2015
# Copyright:   (c) Yang 2015
# Licence:     <your licence>
#-------------------------------------------------------------------------------

from PyQt4 import QtGui,QtCore

class %(class_name)s(QtGui.QWidget):
    def __init__(self, parent=None):
        super(%(class_name)s, self).__init__(parent)
        self.items = parent.items if parent else {}
        self.__init_datas()
        self.__create_items()
        self.__set_events()
##        self.setModal(True)
        self.setWindowTitle(u"%(class_title)s")
##        self.setWindowFlags(QtCore.Qt.Dialog|QtCore.Qt.WindowCloseButtonHint)
        self.trans = {"window_title":"%(class_trans)s"}
        self.items["%(class_prefix)s_ui"] = self
        self.__trans_items()

    def __init_datas(self):
        self.data = {}
        self.data["mc_id"] = None
        self.data["snaddr"] = "FF"
        self.data["spaddr"] = "FF"
        self.data["rcaddr"] = "FFFF"
        self.data["operation"] = None
        self.data["mode"] = "save"
        self.data["argvs"] = []

    def __create_items(self):
        pass

    def __set_events(self):
        pass

    def __set_ui_config(self):
        """将数据表示到画面"""
        pass

    def __get_ui_config(self):
        """将画面数据保存到结构体"""
        pass

    def __trans_items(self):
        if self.parent() is None:
            return
        self.parent().trans_items("%(class_prefix)s")

    def __send_request(self, data, show_msg=0, msg_revc=None):
        if self.parent() is None:
            return {}
        if data["mc_id"] is None:
            return {}
        return self.parent().send_request(data, show_msg, msg_revc)

    def showEvent(self, event):
        super(%(class_name)s, self).showEvent(event)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()
        super(%(class_name)s, self).keyPressEvent(event)


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    dialog = %(class_name)s()
    dialog.show()
    sys.exit(app.exec_())

这个是配置文件(config.json),主要是为了方便模板文件修改之后,不用修改自动生成文件的代码。

{
    "template_file":"widget_template.txt",
    "file_name":"SplashSettings.py",
    "class_name":"SplashSettings",
    "class_trans":"splash_setting",
    "class_title":"开机画面设置",
    "class_prefix":"sd_ss"
}

下面是自动生成文件的代码(widget_robot.py)

# -*- coding: UTF-8 -*-
#!/usr/bin/env python

#-------------------------------------------------------------------------------
# Name:        UI自动生成工具
# Purpose:
#
# Author:      Yang
#
# Created:     13/08/2015
# Copyright:   (c) Yang 2015
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import json
import codecs

def main():
    # read config
    config = {}
    with codecs.open("config.json","rb","UTF-8") as f:
        config = json.loads(f.read())
    if not config:
        return

    # read template file
    s = ""
    template = config.get("template_file", "widget_template.txt")
    with codecs.open(template, "rb", "UTF-8") as f:
        s = f.read()
    if not s:
        return
    s = s % config

    # save to file
    fn = config["file_name"]
    with codecs.open(fn, "wb", "UTF-8") as f:
        f.write(s)
        f.flush()

if __name__ == '__main__':
    try:
        main()
    except Exception,ex:
        print(ex)

总结:

    其实很简单的,只要是写过代码的人都能写出来。关键看你想不想去写。

    第一次写笔记。祝我在程序员的道路上越走越远。









转载于:https://my.oschina.net/yangch/blog/492099

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值