ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • yaml / configparser
    python/응용 2022. 5. 21. 23:26

    YAML config

    https://pypi.org/project/PyYAML/3.10/ Install

    config.yml

    DEFAULT:
      debug: true
    web_server:
      host: 127.0.0.1
      port: 80

     

    위의 config.yml 파일 생성하기

    import yaml
    
    with open('config.yml', 'w') as yaml_file:
        yaml.dump({
            'DEFAULT': {
                'debug': True
            },
            'web_server': {
                'host': '127.0.0.1',
                'port': 80
            }
        }, yaml_file)

     

    위의 config.yml 파일 읽기

    import yaml
    
    with open('config.yml', 'r') as yaml_file:
        config = yaml.safe_load(yaml_file)
    
    print(config)
    print(config['DEFAULT']['debug'])
    print(config['web_server']['host'])

     

    INI config

    config.ini

    [DEFAULT]
    debug = True
    
    [web_server]
    host = 127.0.0.1
    port = 80

     

    위의 config.ini 파일 생성하기

    import configparser
    
    config = configparser.ConfigParser()
    config['DEFAULT'] = {
        'debug': True
    }
    
    config['web_server'] = {
        'host': '127.0.0.1',
        'port': 80
    }
    
    with open('config.ini', 'w') as config_file:
        config.write(config_file)

     

    위의 config.ini 파일 읽기

    config = configparser.ConfigParser()
    config.read('config.ini')
    
    print(config['DEFAULT']['debug'])
    print(config['web_server']['host'])
    print(config['web_server']['port'])

    'python > 응용' 카테고리의 다른 글

    pytest - fixture  (0) 2022.05.23
    pytest - basic  (0) 2022.05.23
    Thread - queue & PoisonPill  (0) 2022.05.23
    logging  (0) 2022.05.22
    optparse  (0) 2022.05.22

    댓글

Designed by Tistory.