当前位置:网站首页>Use of command line parameter passing library argparse
Use of command line parameter passing library argparse
2022-04-23 07:46:00 【Apple Laboratory of Central South University】
author :18cyl
Time :2022.4.20
Reference article :python argparse: Command line parameter details
This paper is mainly a supplement to the above article
One 、 Common parameter combinations
parser = argparse.ArgumentParser(description="Something about the program") # Basically just description This field is enough Or nothing
# Basically, I only use long options and optional parameters
parser.add_argument('--weights', type=str, default='123456', help='initial weights') # belt default String parameter of
parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')# flag value The format is value, nothing flag It's empty string . Don't allow alone flag
parser.add_argument('--bucket', nargs='?',const="",default='', help='gsutil bucket')# Accept to flag Or nothing flag Are empty strings ,flag value The format is value
parser.add_argument('--epochs', type=int, default=300,help='initial epochs')# belt default Of int Type parameter
parser.add_argument('--rect', action='store_true', help='rectangular training') # Acceptance is true, Default not received False, Not allowed flag value This assignment format
parser.add_argument('--rect', action='store_false', help='rectangular training') # Acceptance is false, Default not received true, Not allowed flag value This assignment format
parser.add_argument('--resume', action="store_const",const=5, default=False, help='resume most recent training')# Accept to --resume Then for 5(const), If not received, it is False(default) Not allowed flag value The format of store_true、store_false yes store_const A special form of
# nargs ‘?’ Indicates at most one ,‘+’ It means at least one ,‘*’ There can be any , A number indicates that you must specify a number of
# When the command line passes through multiple parameters, the format is flag value1 value2 value3. If not specified type by int And so on, the default is str,
# nargs by ?* Or greater than 1 The accepted results are list. Even if only one number is accepted
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')# belt default The majority of int type
parser.add_argument('--resume', nargs='?', const=1, default=False, help='resume most recent training') # Received --resume If there is no belt in the back value Save as 1, If you receive --resume value1 The format is saved as value1 If not received --resume Then for False
opt = parser.parse_args() # 3、 Using parser object built-in methods , Start parsing parameters , Get parsing result object Namespace(about='input')
print(opt)
print(opt.about) # 4、opt To parse the result object adopt Instance variables Get the parameters passed in from the command line
Two 、 Using frames
There are four steps :
import argparse
parser = argparse.ArgumentParser() #1、 initialization ArgumentParser() object namely : Get parser object
parser.add_argument("-a","--about",type=str,help="this is a para named about") #2、 Using parser object built-in methods , Add parameter resolution rules See the following article for specific rules
opt = parser.parse_args() # 3、 Using parser object built-in methods , Start parsing parameters , Get parsing result object Namespace(about='input')
print(opt)
print(opt.about) # 4、opt To parse the result object adopt Instance variables Get the parameters passed in from the command line
See here some doubt : The input is -a Parameters But the result is only about Value ? In front of the parameter -|– What does that mean? ? If the hands-on experiment finds print(opt.a) Why the report is wrong ? Then go on Watch and experiment Well ! If you have any questions, please feel free to comment in the comments area !
3、 ... and 、 Instructions
- perform python test.py -h
Explain each part : The difference between positional parameters and optional parameters Explain later . The rest usage Field 、Desctiption Field 、 The contents in the supplementary description field can be through
argparse.ArgumentParser() #1、 initialization
Set when obtaining the resolution object
# usage Field
usage: The program name [-h|--help] .....
# Description Field
Program function description
# Description of position parameters ( Mandatory )
positional arguments:
...
# Optional parameter description
optional arguments:
...
# Additional description fields
...
Parameter description :
2. Test use argparse.ArgumentParser()
Show me :
import argparse
parser = argparse.ArgumentParser(prog="Test.py",usage="Good-usage",description="OK-description",epilog="Yes-epilog") # initialization ArgumentParser() object namely : Get parser object
parser.add_argument("-a","--about",type=str,help="this is a para named about") # Using parser object built-in methods , Add parameter resolution rules See the following article for specific rules
opt = parser.parse_args() # Using parser object built-in methods , Start parsing parameters , Get parsing result object
print(opt)
print(opt.about)
So you can see usage Field , If it doesn't change , People will automatically display the parameters of this program , It's better not to add .epilog、description、usage Personal feelings all play an explanatory role . therefore You can just use description Field , Other automatic defaults are fine . as for prog Field , I don't see any bird use .
- Introduce parser.add_argument() Parameters in
- name And flags The difference between
My understanding is that No - perhaps – Means name, This parameter is classified as positional argument Positional arguments , With -|– Yes. flags, The parameters in this form are classified as optional argument Optional parameters .flags Is designed for long and short options , See the figure below for details
It should be noted that :1、 One add_argument() Can't appear at the same time name and flags( Two kinds of flags None of the parameters of the format )
2、positional argument Positional parameters are on the command line They must be assigned in order , Can only be assigned by relative position, not by name=value This form , Readability is extremely unfriendly , Because it must be assigned a value , therefore default The default value is nothing ,required Nor can it be used with position parameters , If one of the parameters uses nargs=“*” perhaps + The representative can accept one or more , After setting the number of variable parameters of zero or more parameters , Extremely unfriendly to use . Pure advice is not to
parser.add_argument("e",type=str,default="123",help="this is a positional argument") #nagrs You can set how many numbers this parameter can accept
parser.add_argument("f",type=str,default="123",help="this is a positional argument")
3、optional argument Optional parameters can appear in one of the long options or at the same time , It defaults to... Even if you don't enter it None, The input mode is in name value The format of ( There is a space in the middle ) If this parameter receives more than one parameter, use name value1 value2 … The format of How many parameters are received in order to nargs This field controls .
import argparse
parser = argparse.ArgumentParser(description="this is a test about argparse") # initialization ArgumentParser() object namely : Get parser object
parser.add_argument("-a","--about",type=str,default="123",required=False,help="this is an optional argument named about") # Using parser object built-in methods , Add parameter resolution rules See the following article for specific rules
parser.add_argument("-b",type=str,help="this is an optional argument")
parser.add_argument("--c",type=str,help="this is an optional argument")
opt = parser.parse_args() # Using parser object built-in methods , Start parsing parameters , Get parsing result object
print(opt)
# print(opt.about)
It is worth noting that Used in the program is opt.about, Not at all opt.–about To get about The value of this , If the long option and the short option appear at the same time ,opt.a( Short options ) It's a mistake , The passed in parameters can only be obtained through the long option .
4. action Field usage
When the command line receives a message with action Field , Actions performed
More commonly used is store_true And store_false. That is, when receiving the parameter, set the value of the parameter to True perhaps False, If no value is received , The default setting is default Corresponding value , without default The fields are False perhaps True,.
Need to pay attention to when , When using the store_true perhaps store_false When Out of commission flag value The format of , and There can only be one flag( After all, it's not an assignment operation ) also Cannot be associated with type Fields appear at the same time .
parser.add_argument("-a","--about",action="store_true",required=False,help="this is an optional argument named about") # Using parser object built-in methods , Add parameter resolution rules See the following article for specific rules
parser.add_argument("-b",action="store_false",help="this is an optional argument")
parser.add_argument("--c",type=str,help="this is an optional argument")
版权声明
本文为[Apple Laboratory of Central South University]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230626397576.html
边栏推荐
猜你喜欢
随机推荐
Preliminary configuration of OpenGL super Dictionary (freeglut, glew, gltools, GLUT)
Window10版MySQL设置远程访问权限后不起效果
C# 读取注册表
SAP Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃。
10. Update operation
自己封装unity的Debug函数
4. Multi table query
Moment. Format of format method function in JS
c#读取INI文件和向ini文件写入数据
解决在docker中部署mysql8, 密码正确但无法登陆MySQL问题
SAP pi / PO rfc2restful publishing RFC interface is a restful example (proxy indirect method)
简单理解==和equals,String为什么可以不用new
颜色转换公式大全及转换表格(31种)
promise all的实现
将指定路径下的所有SVG文件导出成PNG等格式的图片(缩略图或原图大小)
unity UGUI判断点击在UI上和3D物体上的解决方案
系统与软件安全研究(二)
2022.3.14 Ali written examination
SAP PI/PO rfc2Soap 发布rfc接口为ws示例
斐波拉去动态规划