美文网首页
2020-08-16

2020-08-16

作者: ufopp12 | 来源:发表于2020-08-16 21:39 被阅读0次

    python 获取配置文件的几种方法

    1.以变量的方式读取

    代码示例

    [root@132 test]~ cat config.py
    \#!/usr/bin/env  python
    \#_*_coding:utf-8_*_
    name = "ufopp12"
    age = 30
    job = 'devops'
    

    配置文件

    \#!/usr/bin/env  python
    \#_*_coding:utf-8_*_
    
    import config
    name = config.name
    age = config.age
    job = config.job
    
    print "my name is {0} ane age is {1},Im doing {2}".format(name,age,job)
    

    输出

    [root@132 test]\# python test.py 
    my name is ufopp12 ane age is 30,Im doing devops
    

    2.python 2 中有个ConfigParser模块可以读取变量

    示例

    import ConfigParser
    
    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    print config.sections()  #列出所有sections
    
    for item,value in config.items('type1'):
        item = value  # 获取type1中所有变量
    print name,age
    
    print config.get('type2','name') #获取tpye2中name变量的值
    

    输出

    ['type1', 'type2']
    ufopp12 30
    "mack"
    

    配置文件

    cat config.ini
    [type1]
    name = "ufopp12"
    age = 30
    job = 'devops'
    [type2]
    name = "mack"
    age = 19
    job = 'student'
    

    3.以json方式读取变量

    代码

    import json
    f = open('config.json','r')
    text = json.loads(f.read())
    name = text[0]['name']
    print type(text),name
    

    配置文件

    [root@132 test]\# cat config.json 
    [
            {
            "name":"ufopp12",
            "age":30,
            "job":"devops"
            }
    ]
    
    

    相关文章

      网友评论

          本文标题:2020-08-16

          本文链接:https://www.haomeiwen.com/subject/hyktjktx.html