python简单实现代码生成

这篇博客介绍了如何使用Python脚本GenCode.py,结合config.json配置文件和templatecpp.txt模板,自动生成C++代码,如templatecpp.h头文件。通过实例展示了Python在代码自动化生成中的应用。
摘要由CSDN通过智能技术生成

config.json

{
    "template_file": "templatecpp.txt",
    "class_name": "ConfigLoad",
    "config_name": "TestConfig",
    "settingip_name": "ServerIp",
    "file_name": "templatecpp.h"
}

templatecpp.txt

#include "rapidjson/reader.h"
#include "rapidjson/document.h"
#include <string>
using namespace rapidjson;
using namespace std;

class %(class_name)s
{
public:
    static %(class_name)s &Instance()
    {
        static %(class_name)s instance;
        return instance;
    } 

    bool LoadJson(const std::string& jsonfile)
    {
		std::ifstream f(filename);
		if(f.good())
		{
			std::stringstream buffer;
			buffer << f.rdbuf();
			Dom.Parse(buffer.str().c_str());
			return true;
		}
		return false;        
    }

    std::string GetIp()
    {
        rapidjson::Value& v = Dom["%(config_name)s"]["%(settingip_name)s"];
        return v.GetString();
    }
private:
    Document Dom;
};

GenCode.py

# -*- coding: UTF-8 -*-

import json
import codecs

def main():

    config = {}
    with codecs.open("config.json", "r", "utf-8") as f:
        config = json.loads(f.read())
    if not config:
        return

    s = ""
    template = config.get("template_file", "templatecpp.txt")
    with codecs.open(template, "r", "utf-8") as f:
        s = f.read()
    if not s:
        return

    s = s % config

    file = config["file_name"]
    with codecs.open(file, "w", "utf-8") as f:
        f.write(s)
        f.flush()

if __name__ == '__main__':
     main()

生成代码:

templatecpp.h

#include "rapidjson/reader.h"
#include "rapidjson/document.h"
#include <string>
using namespace rapidjson;
using namespace std;

class ConfigLoad
{
public:
    static ConfigLoad &Instance()
    {
        static ConfigLoad instance;
        return instance;
    } 

    bool LoadJson(const std::string& jsonfile)
    {
		std::ifstream f(filename);
		if(f.good())
		{
			std::stringstream buffer;
			buffer << f.rdbuf();
			Dom.Parse(buffer.str().c_str());
			return true;
		}
		return false;        
    }

    std::string GetIp()
    {
        rapidjson::Value& v = Dom["TestConfig"]["ServerIp"];
        return v.GetString();
    }
private:
    Document Dom;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值