Project Icon

CommandlineConfig

Python命令行配置管理工具

CommandlineConfig是一个Python命令行配置管理工具,支持以字典或JSON格式定义配置,通过点号语法读写参数。它具备无限层级参数嵌套、命令行参数修改、自动版本检查等功能。该工具简化了实验和项目的配置管理流程,适用于各类Python开发场景。

请您Star Please Star

如果你觉得此工具不错,请轻轻点击此页面右上角Star按钮增加项目曝光度,谢谢!

If you think this tool is good, please gently click the Star button in the upper right corner at this page to increase the project exposure, thank you!

中文文档

点此查看中文文档

Easy-to-use Commandline Configuration Tool

A library for users to write (experiment in research) configurations in Python Dict or JSON format, read and write parameter value via dot . in code, while can read parameters from the command line to modify values.

标签 Labels: Python, Command Line, commandline, config, configuration, parameters, 命令行,配置,传参,参数值修改。

Github URL: https://github.com/NaiboWang/CommandlineConfig

Reserved Fields

The following fields are reserved and cannot be used as parameter names: config_name.

New Features

v2.2.*

  • Support infinite level nesting of parameters in dictionary
  • Automatic version checking
  • Support parameter value constrained to specified value (enumeration)
  • Support for tuple type
  • Support reading configuration from local JSON file
  • Support for setting parameter help and printing parameter descriptions via command line -h
  • Documentation updates, provide simple example

Simple Example

# Install via pip
pip3 install commandline_config

# import package
from commandline_config import Config

# Define configuration dictionary
config = {
  "index":1,
  "lr": 0.1,
  "dbinfo":{
    "username": "NUS"
  }
}

# Generate configuration class based on configuration dict
c = Config(config)

# Print the configuration of the parameters
print(c)

# Read and write parameters directly via dot . and support multiple layers.
c.index = 2
c.dbinfo.username = "ZJU"
print(c.index, c.dbinfo.username, c["lr"])

# On the command line, modify the parameter values with --
python example.py --index 3 --dbinfo.username XDU

# Get the parameter descriptions via the help method in the code, or on the command line via -h or -help (customization required, see detailed documentation below for details)
c.help()

python example.py -h

Catalogue

Usage

Please submit issue

If you encounter any problems during using with this tool, please raise an issue in the github page of this project, I will solve the bugs and problems encountered at the first time.

Meanwhile, welcome to submit issues to propose what functions you want to add to this tool and I will implement them when possible.

Installation

There are two ways to install this library:

    1. Install via pip:
    pip3 install commandline_config
    

    If already installed, you can upgrade it by the following command:

    pip3 install commandline_config --upgrade
    
    1. Import the commandline_config.py file directly from the /commandline_config folder of the github project into your own project directory, you need to install the dependency package prettytable:
    pip3 install prettytable
    

    Or install via requirements.txt:

    pip3 install -r requirements.txt
    

Configuration Way

    1. Import library:
    from commandline_config import Config
    
    1. Set the parameter name and initial value in JSON/Python Dict format, and add the parameter description by # comment. Currently supports nesting a dict inside another dict, and can nest unlimited layers.
    preset_config = {
          "index": 1,  # Index of party
          "dataset": "mnist",
          'lr': 0.01,  # learning rate
          'normalization': True,
          "pair": (1,2),
          "multi_information": [1, 0.5, 'test', "TEST"],  # list
          "dbinfo": {
              "username": "NUS",
              "password": 123456,
              "retry_interval_time": 5.5,
              "save_password": False,
              "pair": ("test",3),
              "multi":{
                  "test":0.01,
              },
              "certificate_info": ["1", 2, [3.5]],
          }
      }
    

    That is, the initial configuration of the program is generated. Each key defined in preset_config dict is the parameter name and each value is the initial value of the parameter, and at the same time, the initial value type of the parameter is automatically detected according to the type of the set value.

    The above configuration contains seven parameters: index, dataset, batch, normalization, pair, multi_information and dbinfo, where the type of the parameter index is automatically detected as int, the default value is 1 and the description is "Index of party".

    Similarly, The type and default value of the second to fifth parameter are string: "mnist"; float:0.01; bool:True; tuple:(1,2); list:[1,0.5,'test', "TEST"].

    The seventh parameter is a nested dictionary of type dict, which also contains 7 parameters, with the same type and default values as the first 7 parameters, and will not be repeated here.

    1. Create a configuration class object by passing preset_config dict to Config in any function you want.
    if __name__ == '__main__':
        config = Config(preset_config)
        # Or give the configuration a name:
        config_with_name = Config(preset_config, name="Federated Learning Experiments")
    
        # Or you can store the preset_config in local file configuration.json and pass the filename to the Config class.
        config_from_file = Config("configuration.json")
    

    This means that the configuration object is successfully generated.

    1. Configuration of parameters can be printed directly via print function:
    print(config_with_name)
    

    The output results are:

    Configurations of Federated Learning Experiments:
    +-------------------+-------+--------------------------+
    |        Key        |  Type | Value                    |
    +-------------------+-------+--------------------------+
    |       index       |  int  | 1                        |
    |      dataset      |  str  | mnist                    |
    |         lr        | float | 0.01                     |
    |   normalization   |  bool | True                     |
    |        pair       | tuple | (1, 2)                   |
    | multi_information |  list | [1, 0.5, 'test', 'TEST'] |
    |       dbinfo      |  dict | See sub table below      |
    +-------------------+-------+--------------------------+
    
    Configurations of dict dbinfo:
    +---------------------+-------+---------------------+
    |         Key         |  Type | Value               |
    +---------------------+-------+---------------------+
    |       username      |  str  | NUS                 |
    |       password      |  int  | 123456              |
    | retry_interval_time | float | 5.5                 |
    |    save_password    |  bool | False               |
    |         pair        | tuple | ('test', 3)         |
    |        multi        |  dict | See sub table below |
    |   certificate_info  |  list | ['1', 2, [3.5]]     |
    +---------------------+-------+---------------------+
    
    Configurations of dict multi:
    +------+-------+-------+
    | Key  |  Type | Value |
    +------+-------+-------+
    | test | float | 0.01  |
    +------+-------+-------+
    

    Here the information of all parameters will be printed in table format. If you want to change the printing style, you can modify it by config_with_name.set_print_style(style=''). The values that can be taken for style are: both, table, json which means print both table and json at the same time, print only table, and json dictionary only.

    E.g.:

    # Only print json 
    config_with_name.set_print_style('json')
    print(config_with_name)
    print("----------")
    # Print table and json at the same time
    config_with_name.set_print_style('table')
    print(config_with_name)
    

    The output results are:

    Configurations of Federated Learning Experiments:
    {'index': 1, 'dataset': 'mnist', 'lr': 0.01, 'normalization': True, 'pair': (1, 2), 'multi_information': [1, 0.5, 'test', 'TEST'], 'dbinfo': 'See below'}
    
    Configurations of dict dbinfo:
    {'username': 'NUS', 'password': 123456, 'retry_interval_time': 5.5, 'save_password': False, 'pair': ('test', 3), 'multi': 'See below', 'certificate_info': ['1', 2, [3.5]]}
    
    Configurations of dict multi:
    {'test': 0.01}
    
    ----------
      
    Configurations of Federated Learning Experiments:
    +-------------------+-------+--------------------------+
    |        Key        |  Type | Value                    |
    +-------------------+-------+--------------------------+
    |       index       |  int  | 1                        |
    |      dataset      |  str  | mnist                    |
    |         lr        | float | 0.01                     |
    |   normalization   |  bool | True                     |
    |        pair       | tuple | (1, 2)                   |
    | multi_information |  list | [1, 0.5, 'test', 'TEST'] |
    |       dbinfo      |  dict | See sub table below      |
    +-------------------+-------+--------------------------+
    {'index': 1, 'dataset': 'mnist', 'lr': 0.01, 'normalization': True, 'pair': (1, 2), 'multi_information': [1, 0.5, 'test', 'TEST'], 'dbinfo': 'See below'}
    
    Configurations of dict dbinfo:
    +---------------------+-------+---------------------+
    |         Key         |  Type | Value               |
    +---------------------+-------+---------------------+
    |       username      |  str  | NUS                 |
    |       password      |  int  | 123456              |
    | retry_interval_time | float | 5.5                 |
    |    save_password    |  bool | False               |
    |         pair        | tuple | ('test', 3)         |
    |        multi        |  dict | See sub table below |
    |   certificate_info  |  list | ['1', 2, [3.5]]     |
    +---------------------+-------+---------------------+
    {'username': 'NUS', 'password': 123456, 'retry_interval_time': 5.5, 'save_password': False, 'pair': ('test', 3), 'multi': 'See below', 'certificate_info': ['1', 2, [3.5]]}
    
    Configurations of dict multi:
    +------+-------+-------+
    | Key  |  Type | Value |
    +------+-------+-------+
    | test | float | 0.01  |
    +------+-------+-------+
    {'test': 0.01}
    

Configuration parameters read and write method

Write method

Configuration parameter values can be written in three ways.

    1. To receive command line arguments, simply pass --index 1 on the command line to modify the value of index to 1. Also, the considerations for passing values to different types of arguments are:

    • When passing bool type, you can use 0 or False for False, 1 or True or no value after the parameter for True: --normalization 1 or --normalization True or --normalization all can set the value of parameter normalization in the configuration to True.
    • When passing list type, empty array and multi-dimensional arrays can be passed.
    • To modify the value in the nested dict, please use --nested-parameter-name.sub-parameter-name.sub-parameter-name.….sub-parameter-name value to modify the value in the nested object, such as --dbinfo.password 987654 to change the value of the password parameter in the dbinfo subobject to 987654; --dbinfo.multi.test 1 to change the value of the test parameter in the multi dict which is in dbinfo subobject to ```. Currently this tool can supports unlimited layers/levels of nesting.
    • Note that the argument index must be in the preset_config object defined above:
    python test.py --dbinfo.password 987654 --dbinfo.multi.test 1 --index 0 --dataset emnist --normalization 0 --multi_information [\'sdf\',1,\"3.3\",,True,[1,[]]] 
    
    1. Use config.index = 2 directly in the code to change the value of the parameter index to 2. Again, list type parameters can be assigned as empty or multidimensional arrays. For nested objects, you can use config.dbinfo.save_password=True to modify the value of the save_password parameter in sub dict dbinfo to True.
    1. Way 1 and 2 will trigger type checking, that is, if the type of the assigned value and the type of the default value in the predefined dict preset_config does not match, the program will report an error, therefore, if you do not want to force type checking, you can use config["index"] = "sdf" to force the value of the parameter index to the string sdf (not recommended, it will cause unexpected impact).

Reading method

Read the value of the parameter dataset directly by means of config.dataset or config["dataset"].

print(config.dataset, config["index"])

The value of an argument a will be read by this order: the last value modified by config.a = * > the value of --a 2 specified by the command line > the initial value specified by "a":1 defined by preset_config.

For the list type, if a multidimensional array is passed, the information can be read via standard slice of python:

config.dbinfo.certificate_info = [1,[],[[2]]]
print(config.dbinfo.certificate_info[2][0][0])

For parameters in a single nested object, there are four ways to read the values of the parameters, all of which can be read successfully:

print(config.dbinfo.username)
print(config["dbinfo"].password)
print(config.dbinfo["retry_interval_time"])
print(config["dbinfo"]["save_password"])

Pass configuration to functions

Simply pass the above config object as a parameter to the function and call it:

def print_dataset_name(c):
  print(c.dataset, c["dataset"], c.dbinfo.certificate_info)

print_dataset_name(c=config)

Copy configuration

A deep copy of the

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号