zoukankan      html  css  js  c++  java
  • PyYAML模块和ConfigParser模块

    两模块都是用来处理配置文件

    PyYAML可参考 http://pyyaml.org/wiki/PyYAMLDocumentation

    常见的文档格式,eg:

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    Forwardx11 = yes
    
    [bitbucket.org]
    User = hg
    
    [topsecret.server.com]
    Port = 50022
    Forwardx11 = no

    用configparser生成这样的文件

    import configparer  # Python2 ConfigParser
    
    config = configparser.ConfigParser()
    
    config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}
    
    config['bitbucket.org'] = {}
    config['bitbucket.org']['User'] = 'hg'
    
    config['topsecret.server.com'] = {}
    topsecret = config['topsecret.server.com']
    topsecret['Host Port'] = '50022'
    topsecret['ForwardX11'] = 'no'
    config['DEFAULT']['ForwardX11'] = 'yes'
    
    with open('example.ini', 'w') as configfile:
        config.write(configfile)

    >>> import configparser
    >>> config = configparser.ConfigParser()
    >>> config.read('example.ini')
    ['example.ini']
    >>> print(config.sections)
    <bound method RawConfigParser.sections of <configparser.ConfigParser object at 0x000001FC2367EFD0>>
    >>> print(config.sections())
    ['bitbucket.org', 'topsecret.server.com']
    >>> print(config.defaults())
    OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45'), ('forwardx11', 'yes')])
    >>> print(config['bitbucket.org'])
    <Section: bitbucket.org>
    >>> print(config['bitbucket.org']['user'])
    hg
    >>> sec = config.remove_section('bitbucket.org') # 删
    >>> config.write(open('exmple.cfg', 'w'))
  • 相关阅读:
    2019春第三次课程设计实验报告
    2019 春第二次课程设计实验报告
    2019 春第一次课程设计实验报告
    第十二周作业
    第十一周作业
    第十周作业
    IDEA部署好WEB项目调用servlet时报错404
    软件工程作业02
    软件工程作业01
    Java实验报告六
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/9226549.html
Copyright © 2011-2022 走看看