Python使用模板自動產生代碼

來源:互聯網
上載者:User

標籤:

整體思想:

      完全按照自己的想法來寫的,首先寫模板檔案,然後開啟模板檔案,對模板進行字串格式化處理,最後再將格式化後的字串儲存到新的檔案裡面。如有更好的想法,歡迎交流。

將相似性很高的代碼寫模板檔案(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,QtCoreclass %(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 jsonimport codecsdef 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)

總結:

    其實很簡單的,只要是寫過代碼的人都能寫出來。關鍵看你想不想去寫。

    第一次寫筆記。祝我在程式員的道路上越走越遠。









Python使用模板自動產生代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.