Describes how to set parameters using configparser, which is a standard library of python, and how to use setting parameters.
git : k-washi
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 the config.ini file and settings. For logger, please refer to How to use Python logging module.
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))
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
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