zoukankan      html  css  js  c++  java
  • python配置文件转dict

    配置文件有很多种,如JSON,properties,conf,xml等。
    除非需要跟别的语言进行交互,python本身是完全可以取代所有配置文件的。使用python进行配置可以使用非常灵活地执行一些逻辑运算,这点是JSON、XML等格式所无法比拟的,但是配置文件中掺入太多的逻辑并不是好方法。
    将python版的配置文件转化为其它格式非常简单,只需要写一个函数即可

    首先创建一个config.py文件,里面的配置包含int,str,dict,list等类型的数值。
    config.py

    one = 1
    two = 2
    three = one + two
    four = {
        "one": 1,
        "two": 2,
        "three": 3
    }
    five = "天下大势为我所控"
    six=[one,two,three]
    

    然后创建load.py,实现to_dict函数

    import config
    import json
    
    
    def to_dict(config):
        ans = dict()
        for i in dir(config):
            if i.startswith("__"): continue
            x = getattr(config, i)
            if type(x) in (dict, int, str, float,list):
                ans[i] = x
        return ans
    
    
    class config2:
        one = 1
        two = 2
        three = one + two
        four = {
            'one': 1,
            'two': 2
        }
        five = "天下大势为我所控"
        six = [one, two, three]
    
    
    print(json.dumps(to_dict(config), ensure_ascii=0))
    print(json.dumps(to_dict(config2), ensure_ascii=0))
    
  • 相关阅读:
    Django模板系统
    __new__与__init__的区别
    django中models field详解
    快速入门mysql
    jq2
    jq
    前端 js 部分
    前端 js
    前端 css
    前端 table form
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/8079185.html
Copyright © 2011-2022 走看看