016_python程序变量抽取配置的几种方式

一、json配置文件

json文件的互转,如下例子:

配置文件:example.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
    "mysql":{
        "host":"localhost",
        "user":"root",
        "passwd":"my secret password",
        "db":"write-math"
    },
    "other":{
        "preprocessing_queue":[
            "preprocessing.scale_and_center",
            "preprocessing.dot_reduction",
            "preprocessing.connect_lines"
            ],
        "use_anonymous":true
    }
}

(1)把字典转换为json配置文件

1
2
3
with open('example.json') as json_data_file:
    data = json.load(json_data_file)
print(data)

输出:

1
{u'other': {u'preprocessing_queue': [u'preprocessing.scale_and_center', u'preprocessing.dot_reduction', u'preprocessing.connect_lines'], u'use_anonymous': True}, u'mysql': {u'passwd': u'my secret password', u'host': u'localhost', u'db': u'write-math', u'user': u'root'}}

(2)再转化为文件:

1
2
with open('result.json', 'w') as fp:
    json.dump(data, fp , indent=4)

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
    "other": {
        "preprocessing_queue": [
            "preprocessing.scale_and_center",
            "preprocessing.dot_reduction",
            "preprocessing.connect_lines"
        ],
        "use_anonymous": true
    },
    "mysql": {
        "passwd": "my secret password",
        "host": "localhost",
        "db": "write-math",
        "user": "root"
    }
}

二、ini配置文件

config.ini

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
; config.ini
; Sample configuration file
 
[installation]
library=%(prefix)s/lib
include=%(prefix)s/include
bin=%(prefix)s/bin
prefix=/usr/local
 
# Setting related to debug configuration
[debug]
log_errors=true
show_warnings=False
 
[server]
port: 8080
nworkers: 32
pid-file=/tmp/spam.pid
root=/www/root
signature:
    =================================
    Brought to you by the Python Cookbook
    =================================

python test.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('config.ini')                      # ['config.ini']
 
print cfg.sections()                        # [u'installation', u'debug', u'server']
print cfg.get('installation','library')     # /usr/local/lib
print cfg.getboolean('debug', 'log_errors') # True
print cfg.getint('server','port')           # 8080
print cfg.getint('server','nworkers')       #32
print(cfg.get('server','signature'))
'''
=================================
Brought to you by the Python Cookbook
=================================
'''

 

posted @   arun_python  阅读(297)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· Supergateway:MCP服务器的远程调试与集成工具
· C# 13 中的新增功能实操
点击右上角即可分享
微信分享提示