Try to write the configuration file in Python instead of .ini etc. ** and give it **.
The configuration file given by writing in Python is like "trial-config1.py" below if you write the setting in the "config (cfg)" function and assign the setting value to the "cfg" object. (Example).
** Function return value ** and ** can be set separately for each case **. It is also possible to read another configuration file and overwrite (nested) it.
trial-config1.py (setting file)
# -*- coding: utf-8 -*-
#Configuration file by py
import socket
# sec: config
def config(cfg):
# sec:Substituting the setting value into cfg
cfg.setting1 = True
# sec:Function return value can be set
cfg.name = socket.gethostname() #hostname(★ Function return value can be set)
cfg.ip = socket.gethostbyname(cfg.name) #IP address
# sec:Can be set separately for each case
if "PC" in cfg.name: # (★ Can be set separately for each case)
cfg.setting2 = True
# sec:Can be set hierarchically
cfg.setting3 = cfg.__class__() # (★ Can be set hierarchically)
cfg.setting3.setting1 = True
# sec:Configuration files can be nested
__import__("trial-config2").config(cfg) # (★ Configuration files can be nested)
Another configuration file also uses the "config (cfg)" function and "cfg" object, and is something like "trial-config2.py" below (example).
trial-config2.py (setting file)
# -*- coding: utf-8 -*-
#Configuration file by py
# sec: config
def config(cfg):
# sec:Overwrite the original settings
cfg.name += " +Overwrite"
cfg.ip += " +Overwrite"
# sec:Substitute new settings
cfg.setting11 = True
When "trial-config1.py" and "trial-config2.py" are placed as follows,
:File structure:
App side script.py
trial-config/
trial-config1.py (setting file)
trial-config2.py (setting file)
To read and use the configuration file written in Python above on the application side, read it with "** __ import__ (" trial-config1 "). Config (cfg) **" etc., and each in "cfg" In the form of using the value, the following code.
App side script.py
# -*- coding: utf-8 -*-
#How to configure and nest configuration definition files with py
import sys
# sec: main
def main():
# sec:Storage class
class Config: pass
cfg = Config()
# sec:Read
sys.path.append(r"./trial-config/")
__import__("trial-config1").config(cfg)
del sys.path[-1]
# sec:Result display
for key, val in cfg.__dict__.items():
print(f"{key}: {val}")
"""Console output example:
setting1: True
name: PC1 +Overwrite
ip: 192.168.0.1 +Overwrite
setting2: True
setting3: <__main__.trail__py_config_file.<locals>.Config object at 0x0>
setting11: True
"""
# sec: entry
if __name__ == "__main__": main()
All the settings in "cfg" are displayed on the console. On the application side, you can use the setting value like "cfg.setting1".
Recommended Posts