Most applications need some configuration parameters. There is different ways to store and use configuration data in software. It is recommended to separate the code an logic modules from the configuration data. This way users will be able to modify or update configuration parameters with no need to modify the application. A simple way to store configuration info is a file with an easy structure that the user can manage. We can take advantage of the package "configparser" in python to read a config file. This is simple cheatsheet to give an example of use.
pip install configparser
2. Define the config file. You can get more info about the config INI file structure in the python documentation. Here an example:
[GLOBAL]
unsername = user
password = pass
prn = 124
[PRN120]
ip = 192.168.1.120
port = 1237
[PRN124]
ip = 192.168.1.124
port = port = 1238
[PRN126]
ip = 192.168.1.126
port = port = 1239
We use config = configparser.ConfigParser()
or config = configparser.RawConfigParser()
to read the config file. With ConfigParser()
you will have to scape the "%" Characters as "%%". So if you are planning to for example use "%" character in your password parameter better use RawConfigParser()
.
import configparser
config_file = "config.ini"
config = configparser.RawConfigParser()
config.read(config_file)
username = config['GLOBAL']['username']
password = config['GLOBAL']['password']
prn = config['GLOBAL']['prn']
ip = config['PRN%s' % prn]['ip']
port = int(config['PRN%s' % prn]['port'])
I hope you find this info useful.
Enjoy !