Parameter setting by python configparser

Describes how to set parameters using configparser, which is a standard library of python, and how to use setting parameters.

git : k-washi

Ini file

This file describes the settings to be read by configparser. As an example, it can be described as follows. Comments can be written using #.

config.ini


[Microphone]
#Mike ID
ID = 0
SamplingRate = 44100

[Output]
#Output device ID
ID = 1
#Record 1:Output to SavePath, 0:Continue to output to the device of ID.
Record = 1
#recording time [sec] >= 1
RecordTime = 15

Read configuration file

Read the config.ini file and settings. For logger, please refer to How to use Python logging module.

  1. If there is a configuration file, read the configuration file with config_ini.read ().
  2. Read the setting value with config_ini ["setting classification"] ["setting value name"].

Since the read setting value is a string, the numbers are converted with int, float, etc. Also, the Yes / No value set by 0, 1 can be converted to True, False by setting it to bool.

utils/config.py


import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

# ------------

from utils.logConf import logging
logger = logging.getLogger(__name__)

# -------------

import configparser
CONFIG_FILE_PATH = './config.ini'


class configInit():
  def __init__(self):
    config_ini = configparser.ConfigParser()
    if not os.path.exists(CONFIG_FILE_PATH):
      logger.error('There is no configuration file')
      exit(-1)
    config_ini.read(CONFIG_FILE_PATH, encoding='utf-8')
    logging.info('----Start setting----')
    try:
      self.MicID = int(config_ini['Microphone']['ID'])
      self.SamplingRate = int(config_ini['Microphone']['SamplingRate'])

      self.OutpuID = int(config_ini['Output']['ID'])
      self.Record = bool(int(config_ini['Output']['Record']))
      self.RecordTime = float(config_ini['Output']['RecordTime'])

    except Exception as e:
      logger.critical("config error {0}".format(e))

Use set value

  1. Import the setting class configInit of the setting reading file.
  2. Instantiate with Conf = configInit () and read the config file.
  3. Conf. Can be used with the set value name
import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

# ------------

from utils.config import configInit
Conf = configInit()

from utils.logConf import logging
logger = logging.getLogger(__name__)
# -----------

logger.info(Conf.MicID)
#2020-01-15 17:12:03,929 [config.py:28] INFO     ----Start setting----
#2020-01-15 17:12:03,930 [confTest.py:15] INFO     0                 #MicID

Summary

That's all about the python config file. When creating a system, it is recommended that you set it as easily as above, because there will be less modification when you try to make external settings later.

Recommended Posts

Parameter setting by python configparser
My ConfigParser (Python)
Primality test by Python
Visualization memo by Python
Communication processing by Python
Beamformer response by python
python Environmentally-friendly Japanese setting
EXE Web API by Python
Newcomer training program by Python
Pin python managed by conda
Keyword extraction by MeCab (python)
[Python] numpy.empty initial value setting
Separate numbers by 3 digits (python)
python url setting include function
Markov switching model by Python
Image processing by python (Pillow)
Python started by C programmers
Transfer parameter values in Python
Platform (OS) determination by Python
Sort by date in python
[Python] Sort iterable by multiple conditions
Expansion by argument of python dictionary
[Automation with python! ] Part 1: Setting file
FX Systre Parameter Optimization in Python
HMM parameter estimation implementation in python
Machine learning summary by Python beginners
Learn Python by drawing (turtle graphics)
Python development helped by Jenkins-Unit test
Prime number generation program by Python
python sql statement extracted by time
Make Python dict accessible by Attribute
OS determination by Makefile using Python
Typing automation notes by Python beginners
Vim + Python development environment setting memo
Interval scheduling learning memo ~ by python ~
Behavior of python3 by Sakura's server
100 Language Processing Knock Chapter 1 by Python
Story of power approximation by Python
Sorting files by Python naming convention