Trial of writing the configuration file in Python instead of .ini etc.

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

Trial of writing the configuration file in Python instead of .ini etc.
Download the file in Python
[Note] Import of a file in the parent directory in Python
Google search for the last line of the file in Python
Save the binary file in Python
The story of the "hole" in the file
The idea of feeding the config file with a python file instead of yaml
Check the behavior of destructor in Python
Check the existence of the file with python
The result of installing python in Anaconda
Read the file line by line in Python
In search of the fastest FizzBuzz in Python
[Python] Get the character code of the file
[Python] Read the specified line in the file
[Python3] Understand the basics of file operations
Test & Debug Tips: Create a file of the specified size in Python
Open an Excel file in Python and color the map of Japan
I made a program to check the size of a file in Python
Output the number of CPU cores in Python
[Python] Sort the list of pathlib.Path in natural sort
Match the distribution of each group in Python
View the result of geometry processing in Python
Make a copy of the list in Python
Find the divisor of the value entered in python
The 18th offline real-time writing problem in Python
Find the solution of the nth-order equation in python
The story of reading HSPICE data in Python
[Note] About the role of underscore "_" in Python
About the behavior of Model.get_or_create () of peewee in Python
Solving the equation of motion in Python (odeint)
Convert the character code of the file with Python3
The 19th offline real-time writing problem in Python
Speed evaluation of CSV file output in Python
Get the update date of the Python memo file.
Various ways to read the last line of a csv file in Python
Download the file while viewing the progress in Python 3.x
File operations in Python
Experience the good calculation efficiency of vectorization in Python
Template of python script to read the contents of the file
File processing in Python
How to get the number of digits in Python
[Python] Get the official file path of the shortcut file (.lnk)
[python] Get the list of classes defined in the module
A memo that implements the job of loading a GCS file into BigQuery in Python
the zen of Python
The story of FileNotFound in Python open () mode ='w'
Learn the design pattern "Chain of Responsibility" in Python
Implement the solution of Riccati algebraic equations in Python
File operations in Python
Get the size (number of elements) of UnionFind in Python
Not being aware of the contents of the data in python
Reproduce the execution example of Chapter 4 of Hajipata in Python
Implemented the algorithm of "Algorithm Picture Book" in Python3 (Heapsort)
Output the specified table of Oracle database in Python to Excel for each file
Solve the one-stroke writing (backtrack without recursion in Python)
Get the URL of the HTTP redirect destination in Python
A reminder about the implementation of recommendations in Python
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
Check the asymptotic nature of the probability distribution in Python
Try scraping the data of COVID-19 in Tokyo with Python
Find out the apparent width of a string in python