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

一、json配置文件

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

配置文件:example.json

{
    "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配置文件

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

输出:

{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)再转化为文件:

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

输出:

{
    "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

; 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

#!/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
=================================
'''
扫描二维码关注公众号,回复: 5383097 查看本文章

猜你喜欢

转载自www.cnblogs.com/arun-python/p/10460530.html
今日推荐