CommandlineConfig

CommandlineConfig

Python命令行配置管理工具

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

命令行配置工具Python参数管理JSON格式配置读写Github开源项目

请您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

编辑推荐精选

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI助手AI工具AI写作工具AI辅助写作蛙蛙写作学术助手办公助手营销助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

聊天机器人AI助手热门AI工具AI对话
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

热门AI工具AI办公办公工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

模型训练热门AI工具内容创作智能问答AI开发讯飞星火大模型多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多