Module for providing support for configuration files.
The ConfigClass loads, edits and saves configuration files in JSON format. The data are encapsulated in a single dictionary mapping the variable names (keys) to their values.
ConfigFile is an alternative to the configparse module in Python’s standard libray. While configparser can handle only string values and requires using sections (as in .ini files), ConfigFile is simpler and faster to use, while permits keys and values of any type that a Python dictionary permits.
As it relies on the Python json module, an internal function is called when a values is not known to json, e.g. numpy arrays.
Finally, the function parse_inifile is defined to help reading .ini files.
Examples
Saving a dictionary:
- D = {“username”: “konstantinos”,
“nodes”: [1, 5, 3], “memory”: 1024, “code”: 42, “std.out”: “/data/output/std.out”}
config_file = ConfigFile(“tmp.cfg”) config_file.update(D) config_file.save()
OR
my_config_file = ConfigFile() my_config_file.update(D) my_config_file.save(filename)
Loading and printing configuration:
config = ConfigFile(filename) print(“Loaded a config file with {} entries.”.format(len(config))) print(“The code is”, config[“code”]) print(config)
Altering entries (and creating if non-existing):
config[“machine”] = “supercomputer” config[“code”] = 24 config[“H0 and error”] = (67.8, 0.9)
Loading configuration from multiple files:
config = CongfigFile(“config1.json”) config.load(“config2.json”)
OR
config.load(“config1.json”) config.load(“config2.json”)
If the two loaded configuration files have common keys, then an Exception will occur. To allow updates, e.g. in the case of default configuration and user configuration overriding the former, then:
config = ConfigFile(“default.cfg”) config.load(“user.cfg”, can_update=True)
Iterating entries:
config = ConfigFile(“my_conf.json”)
print(“All configuration items:”) for key in config:
print(” {}: {}”.format(key, config[key]))
print(“Ok, I’ll repeat that…:”) for key, value in config.items():
print(” {}: {}”.format(key, value))
- class posydon.utils.configfile.ConfigFile(path=None)[source]
Bases:
object
Class handling input, process and output of configurations.
Initialize a ConfigFile with or without a path.
- load(path=None, can_update=False)[source]
Load the entries from a JSON file containing a dictionary.