Python: How would you save a simple settings/config file?

后端 未结 6 782
迷失自我
迷失自我 2020-12-04 04:52

I don\'t care if it\'s JSON, pickle, YAML, or whatever.

All other implementations I have seen are not forwards compatible, so

6条回答
  •  遥遥无期
    2020-12-04 05:34

    ConfigParser Basic example

    The file can be loaded and used like this:

    #!/usr/bin/env python
    
    import ConfigParser
    import io
    
    # Load the configuration file
    with open("config.yml") as f:
        sample_config = f.read()
    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.readfp(io.BytesIO(sample_config))
    
    # List all contents
    print("List all contents")
    for section in config.sections():
        print("Section: %s" % section)
        for options in config.options(section):
            print("x %s:::%s:::%s" % (options,
                                      config.get(section, options),
                                      str(type(options))))
    
    # Print some contents
    print("\nPrint some contents")
    print(config.get('other', 'use_anonymous'))  # Just get the value
    print(config.getboolean('other', 'use_anonymous'))  # You know the datatype?
    

    which outputs

    List all contents
    Section: mysql
    x host:::localhost:::
    x user:::root:::
    x passwd:::my secret password:::
    x db:::write-math:::
    Section: other
    x preprocessing_queue:::["preprocessing.scale_and_center",
    "preprocessing.dot_reduction",
    "preprocessing.connect_lines"]:::
    x use_anonymous:::yes:::
    
    Print some contents
    yes
    True
    

    As you can see, you can use a standard data format that is easy to read and write. Methods like getboolean and getint allow you to get the datatype instead of a simple string.

    Writing configuration

    import os
    configfile_name = "config.yaml"
    
    # Check if there is already a configurtion file
    if not os.path.isfile(configfile_name):
        # Create the configuration file as it doesn't exist yet
        cfgfile = open(configfile_name, 'w')
    
        # Add content to the file
        Config = ConfigParser.ConfigParser()
        Config.add_section('mysql')
        Config.set('mysql', 'host', 'localhost')
        Config.set('mysql', 'user', 'root')
        Config.set('mysql', 'passwd', 'my secret password')
        Config.set('mysql', 'db', 'write-math')
        Config.add_section('other')
        Config.set('other',
                   'preprocessing_queue',
                   ['preprocessing.scale_and_center',
                    'preprocessing.dot_reduction',
                    'preprocessing.connect_lines'])
        Config.set('other', 'use_anonymous', True)
        Config.write(cfgfile)
        cfgfile.close()
    

    results in

    [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
    

    XML Basic example

    Seems not to be used at all for configuration files by the Python community. However, parsing / writing XML is easy and there are plenty of possibilities to do so with Python. One is BeautifulSoup:

    from BeautifulSoup import BeautifulSoup
    
    with open("config.xml") as f:
        content = f.read()
    
    y = BeautifulSoup(content)
    print(y.mysql.host.contents[0])
    for tag in y.other.preprocessing_queue:
        print(tag)
    

    where the config.xml might look like this

    
        
            localhost
            root
            my secret password
            write-math
        
        
            
                
  • preprocessing.scale_and_center
  • preprocessing.dot_reduction
  • preprocessing.connect_lines
提交回复
热议问题