CommandlineConfig

Delphi源码 2025-08-14

中文文档

点此查看中文文档

易于使用的命令行配置工具

用户以Python dict或json格式编写的用户编写(实验)配置的库,通过dot .在代码中,虽然可以从命令行读取参数以修改值。

标签标签:python,命令行,命令行,配置,配置,参数,命令行,配置,传参,参数值修改。

github url:https://github.com/naibowang/commandlineconfig

保留字段

以下字段保留,不能用作参数名称: config_name

新功能

v2.2。*

  • 支持字典中参数的无限级别嵌套
  • 自动版本检查
  • 支撑参数值限制为指定值(枚举)
  • 支持元组类型
  • 支持本地JSON文件中的阅读配置
  • 支持通过命令行-h设置参数帮助和打印参数描述
  • 文档更新,提供简单的示例

简单示例

 # 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 

目录

  • 中文文档
  • 易于使用的命令行配置工具
    • 保留字段
    • 新功能
      • v2.2。*
    • 简单示例
    • 目录
    • 用法
      • 请提交问题
      • 安装
      • 配置方式
      • 配置参数读写方法
        • 写方法
        • 阅读方法
        • 将配置传递到功能
        • 复制配置
        • 将配置参数存储到本地文件或数据库
    • 高级选项
      • 将参数输入值限制为固定义务类型
      • 打印参数帮助描述
        • 设置参数描述
        • 打印参数帮助
    • 事情需要注意
      • 与Argparse冲突
      • 输入值强制转换
      • 列表参数需要在字符串元素引用之前通过commandline在字符串元素引用之前分配
      • 引号是元组参数的命令行分配所必需的,并且字符串元素必须先于后斜线
      • 参数命名约定
      • 嵌套对象的无限层
      • 参数完整性检查,所有要修改的参数必须被预定义
      • ZSH环境中的特殊配置
    • 完整的转换示例
    • 示例运行脚本
    • 破碎的想法
    • 托多

用法

请提交问题

如果您在使用此工具期间遇到任何问题,请在此项目的GitHub页面中提出问题,我将第一次解决遇到的错误和问题。

同时,欢迎提交问题以提出要添加到此工具的功能,我将在可能的情况下实施它们。

安装

安装此库有两种方法:

    1. 通过PIP安装:
    pip3 install commandline_config

    如果已经安装,则可以通过以下命令进行升级:

    pip3 install commandline_config --upgrade
    1. 直接从github项目的/commandline_config文件夹直接导入commandline_config.py文件到自己的项目目录中,您需要安装依赖prettytable软件包:
    pip3 install prettytable

    或通过requirements.txt安装.txt:

    pip3 install -r requirements.txt

配置方式

    1. 导入库:
     from commandline_config import Config
    1. 以JSON/Python dict格式设置参数名称和初始值,并通过#添加参数描述。当前,支持嵌套在另一个dict中,并且可以嵌套无限层
     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 ]],
          }
      }

    也就是说,生成程序的初始配置。 preset_config dict中定义的每个密钥是参数名称,每个值是参数的初始值,同时,根据设定值的类型自动检测参数的初始值类型。

    上面的配置包含七个参数: index, dataset, batch, normalization, pair, multi_information and dbinfo ,其中参数索引的类型自动检测为INT ,默认值为1 ,说明为“ party of Party of Party”。

    同样,第二到第五参数的类型和默认值是字符串: "mnist"; float:0.01; bool:True; tuple:(1,2); list:[1,0.5,'test', "TEST"]

    第七参数是类型dict的嵌套字典,它还包含7个参数,具有与前7个参数相同的类型和默认值,并且不会在此处重复。

    1. 通过将preset_config dict传递给您想要的任何函数中的Config来创建一个配置类对象。
     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" )

    这意味着配置对象已成功生成。

    1. 可以通过print功能直接打印参数的配置:
     print ( config_with_name )

    输出结果是:

     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  |
    +------+-------+-------+
    

    在这里,所有参数的信息将以表格格式打印。如果要更改打印样式,则可以通过config_with_name.set_print_style(style='')对其进行修改。可以为style采用的值是: both ,仅打印tablejson的桌子,仅打印表和JSON字典。

    例如:

     # 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 )

    输出结果是:

     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}
    

配置参数读写方法

写方法

配置参数值可以以三种方式编写。

    1. 要接收命令行参数,只需通过命令行上的--index 1即可将index的值修改为1 。同样,将值传递给不同类型的参数的考虑因素是:
    • 当传递布尔类型时,您可以使用0False用于false1Trueno value after the parameter : ---normalization 1--normalization True--normalization函数都可以设置配置中参数normalization值。
    • 传递列表类型时,可以传递空数组和多维数组。
    • 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要更改dbinfo subobject中的multi dict中的test参数的值为````''。当前,此工具可以支持无限的层/嵌套水平。
    • 请注意,参数索引必须在上面定义的preset_config对象中:
     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. 在代码中直接使用config.index = 2将参数index的值更改为2 。同样,列表类型参数可以分配为空或多维数组。对于嵌套对象,您可以使用config.dbinfo.save_password=True True修改sub dict dbinfosave_password参数的值。
    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).

阅读方法

直接通过config.datasetconfig["dataset"]直接读取参数dataset的值。

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

参数a的值将按以下顺序读取:由config.a = * >修改的最后--a 2值由命令行>由preset_config定义的"a":1指定的初始值指定的值。

对于列表类型,如果传递了多维数组,则可以通过Python的标准切片读取信息:

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

对于单个嵌套对象中的参数,有四种方法可以读取参数的值,所有这些都可以成功读取:

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

将配置传递到功能

只需将上述配置对象作为参数传递给该函数,然后将其调用:

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

print_dataset_name ( c = config )

复制配置

可以通过deepcopy方法制作配置对象的深层副本:

 from copy import deepcopy
copy_config = deepcopy ( config )
# Modify new configuration's parameter value, will not affect the orignal configuration
copy_config . index = 15 

将配置参数存储到本地文件或数据库

可以将整个参数配置存储到本地文件中,也可以上传到远程服务器(例如mongodb config.save()将配置存储为config name (or config if there is no name).json

 config . save ( "config/test_config.json" )

然后,我们成功地将配置保存到config文件夹中的local configuration.json文件。文件内容如下:

{
  "index" : 1 ,
  "dataset" : " mnist " ,
  "lr" : 0.01 ,
  "normalization" : true ,
  "pair" : [ 1 , 2 ],
  "multi_information" : [ 1 , 0.5 , " test " , " TEST " ],
  "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 ]]
  }
}

要将其存储到诸如mongodb之类的数据库中,您需要将JSON序列首先获取与info = config.get_config()命令的参数对应,并将其与json库序列化。

例如,将config_with_name配置存储到mongodb

 import pymongo
myclient = pymongo . MongoClient ( 'mongodb://username:example.com:27017/' , connect = False )
mydb = myclient [ 'exps' ]
table = mydb [ "table" ]
# Get the configurations
configuration = config . get_config ()
# Insert configuration dict into mongodb table
table . insert_one ( configuration )

# Or make configuration as part of a bigger dict
all_info = {
  "exp_time" : "20220925" ,
  "configuration" : configuration
}
table . insert_one ( all_info )

请注意,JSON不支持元组,因此无论是在本地还是在数据库中存储,元组参数将转换为列表。

高级选项

将参数输入值限制为固定义务类型

通过将Configoptions传递给Config类,设置高级选项,例如枚举枚举类型。

 option = {}
config = Config ( preset_config , options = option )

如果要将参数的值限制为特定范围,则可以通过配置:

 advanced_options = {
    'lr' : {
        "enum" : [ 0.001 , 15.5 , 0.01 , 0.1 ] # restrict the lr value to one of 0.001, 15.5, 0.01, 0.1
    },
    'index' : {
        "enum" : [ 1 , 2 , 3 ] # Restrict the index value to 1, 2 and 3
    },
    "dbinfo" : {
        "username" : {
            "enum" : [ "XDU" , "ZJU" , "NUS" ] # restrict the dbinfo.username field to XDU, ZJU and NUS
        },
        "multi" :{
            "test" :{
                "enum" : [ 1 , 0.1 , 0.01 , 15 ] # 3 layers nested
            }
        }
    },
}

config = Config ( preset_config , options = advanced_options )

如果设置了枚举,则以下三种方法将参数设置为合格/特殊值以外的值的其他方法都会报告错误。

    1. index的初始值设置为preset_config中的1,2,3以外的值:
     preset_config = {
      "index" : 4 ,
    }
    1. 命令行通过lr参数传递未合格/未指定的值
    python example.py --lr 0.02
    1. 代码将dbinfo.username的值更改为XDU, ZJU and NUS以外的值。
     config . dbinfo . username = "UEST"

    输出是:

    AttributeError: Can not set value 4 because the key ' index ' has set enum list and you the value 4 is not in the enum list [1, 2, 3] !
    
    AttributeError: Can not set value 0.02 because the key ' lr ' has set enum list and you the value 0.02 is not in the enum list [0.001, 15.5, 0.01, 0.1] !
    
    AttributeError: Can not set value nus because the key ' username ' has set enum list and you the value nus is not in the enum list [ ' XDU ' , ' ZJU ' , ' NUS ' ] !

打印参数帮助描述

设置参数描述

通过在Config类中指定helpers参数来设置参数描述帮助者。

 helpers = {
    "index" : "index of information" ,
    "dbinfo_help" : "information dict for database" ,
    "dbinfo" : {
        "username" : "username for database" ,
        "multi" :{
            "test" : "test information"
        }
    }
}

config = Config ( preset_config , helpers = helpers )

请注意,由于dbinfo参数是一个dict ,如果要设置dbinfo的参数描述,则需要设置dbinfo_help参数以在helpers字典中编写描述,即在dict参数之后添加_help添加_help,以设置DICS字段的参数描述。

打印参数帮助

通过在命令行上传递-h-help或调用代码中的help()函数来打印参数描述的两种方法。

 config_with_name . help ()

或者

python example.py -h
# OR
python example.py -help

请注意,它只是一个简短的斜线-没有添加其他命令行参数以获取帮助说明,两种方法的输出是:

 Parameter helps for Federated Learning Experiments:
+-------------------+-------+-------------------------------+
|        Key        |  Type | Comments                      |
+-------------------+-------+-------------------------------+
|       index       |  int  | index of information          |
|      dataset      |  str  | -                             |
|         lr        | float | -                             |
|   normalization   |  bool | -                             |
|        pair       | tuple | -                             |
| multi_information |  list | -                             |
|       dbinfo      |  dict | information dict for database |
+-------------------+-------+-------------------------------+

Parameter helps for dict dbinfo:
+---------------------+-------+-----------------------+
|         Key         |  Type | Comments              |
+---------------------+-------+-----------------------+
|       username      |  str  | username for database |
|       password      |  int  | -                     |
| retry_interval_time | float | -                     |
|    save_password    |  bool | -                     |
|         pair        | tuple | -                     |
|        multi        |  dict | Multiple Parameters   |
|   certificate_info  |  list | -                     |
+---------------------+-------+-----------------------+

Parameter helps for dict multi:
+------+-------+------------------+
| Key  |  Type | Comments         |
+------+-------+------------------+
| test | float | test information |
+------+-------+------------------+

事情需要注意

与Argparse冲突

该库无法与ArgParse库同时读取命令行参数,因此请不要使用args = parser.parse_args()在使用此库时读取命令行参数。

输入值强制转换

参数的类型将被自动检测为preset_config中集合的初始值的相同类型,并且命令行参数的值将被迫转换为相应的类型值,例如上述preset_config dict中index的默认值为1 ,则int索引的类型为1 。如果在命令行上指定--index 15.5 ,则参数index将自动分配给值15 ,也就是说,将自动将15.5自动被迫转换为int类型。

如果不能将命令行参数上指定的参数值强制转换为特定类型,则它将报告一个错误,例如指定的命令行--index sdf ,因为带有string的Orignal格式的SDF无法将字符串的SDF转换为int类型,因此它将报告错误。

列表参数需要在字符串元素引用之前通过commandline在字符串元素引用之前分配

当命令行参数设置为输入list类型时,如果列表中的元素是string,则必须在每个single/double quote之前使用添加backslash \正确解析,否则该参数值将被视为intfloat类型。如果命令行中有spaces ,它们将自动合并(但是命令行环境不能是zsh ,如果它是ZSH环境,则必须删除列表中的所有空格, bashsh没有此问题,也就是说,在ZSH环境中,您不能在-a [ 15和'12'in -a [15, \'12\' --a [15,\'12\'] ]中。

如果可以设置参数如下:

 python test.py --array [1,2.3,\'sdf\'] 

可以正确解析其值为list的数组参数,以及[1,2.3,'sdf', "qwe"]的内容,即同时包含int,float,float,string string data类型的列表。

引号是元组参数的命令行分配所必需的,并且字符串元素必须先于后斜线

当命令行参数设置为输入tuple类型时,指定的元组类型值必须用quotes包含;而且,如果元组中的元素是string ,则必须在每个单个/双引号\之前添加后backslash以进行适当的解析,否则参数值将被视为intfloat类型。同样,如果命令行中有spaces会自动合并(但是命令行环境不能是zsh ,如果它是ZSH环境,则必须删除所有内部空间,bash和sh没有此问题)。

例如,可以将参数设置为

 python test.py --pair "(1,2,\'msg\')"

配对参数的值是类型(1,2, "msg")的元组,即INT类型intfloatstring的元组。

参数命名约定

如果参数名称包含特殊字符,例如-+.spaceother python reserved characters ,您必须使用middle bracket []来读写参数值而不是例如,如果参数名称是multi-information ,则只能通过config["multi-information"]访问,不能执行config.multi-information ,因为负sign -是python语言的保留符号。

嵌套对象的无限层

现在,该工具可以支持嵌套的无限层,其他支持的参数类型是: int, float, string, bool, tuple and list

参数完整性检查,所有要修改的参数必须被预定义

命令行上传递的参数的名称必须在preset_config中定义,否则将报告错误,例如

 python test . py - - arg1 1

由于preset_config dict中未定义参数名称arg1 ,因此报告了一个错误,表明未定义arg1参数。此功能设置为执行参数完整性检查,以避免通过命令行输入错误的参数名称。

ZSH环境中的特殊配置

如果zsh: no matches found ,请在~/.zshrc文件末尾添加setopt no_nomatch ,然后保存后,然后在命令行上运行source ~/.zshrc以刷新ZSH,然后解决问题。

完整的转换示例

argparse工具相比,下面将举一个示例,以说明该工具的便利性。

需要使用argparse工具编写的代码:

 parser = argparse . ArgumentParser ( description = 'PyTorch local error training' )
parser . add_argument ( '--model' , default = 'vgg8b' ,
                    help = 'model, mlp, vgg13, vgg16, vgg19, vgg8b, vgg11b, resnet18, resnet34, wresnet28-10 and more (default: vgg8b)' )
parser . add_argument ( '--dataset' , default = 'CIFAR10' ,
                    help = 'dataset, MNIST, KuzushijiMNIST, FashionMNIST, CIFAR10, CIFAR100, SVHN, STL10 or ImageNet (default: CIFAR10)' )
parser . add_argument ( '--batch-size' , type = int , default = 128 ,
                    help = 'input batch size for training (default: 128)' )
parser . add_argument ( '--num-layers' , type = int , default = 1 ,
                    help = 'number of hidden fully-connected layers for mlp and vgg models (default: 1' )
parser . add_argument ( '--lr' , type = float , default = 5e-4 ,
                    help = 'initial learning rate (default: 5e-4)' )
parser . add_argument ( '--lr-decay-milestones' , nargs = '+' , type = int , default = [ 200 , 300 , 350 , 375 ],
                    help = 'decay learning rate at these milestone epochs (default: [200,300,350,375])' )
parser . add_argument ( '--optim' , default = 'adam' ,
                    help = 'optimizer, adam, amsgrad or sgd (default: adam)' )
parser . add_argument ( '--beta' , type = float , default = 0.99 ,
                    help = 'fraction of similarity matching loss in predsim loss (default: 0.99)' )
args = parser . parse_args ()

args . cuda = not args . no_cuda and torch . cuda . is_available ()
if args . cuda :
    cudnn . enabled = True
    cudnn . benchmark = True

使用此工具转换后要编写的代码:

下载源码

通过命令行克隆项目:

git clone https://github.com/NaiboWang/CommandlineConfig.git