首页 > 编程语言 >python内置库--argparse

python内置库--argparse

时间:2023-05-29 23:44:48浏览次数:36  
标签:default argparse python argument -- 参数 命令行 action

1 关于argparse

从命令行工具运行python时,argparse 可以解析命令行工具输入的各种数据,通过argparse提供的函数或者属性,我们可以获得它解析到的数据

通过argparse,我们也可以自定义命令行选项,比如pytest -s -v ,-s -v就是pytest定义的命令行选项,通过argparse,我们也可以定义自己的命令行选项

下面是一个例子
image
命令行执行 python argparse_a.py a b
image
可以看到在命令行执行python文件时输入的参数 a b,通过argparse,我们得到了这2个参数

现在执行 python argparse_a.py -o ad a b
image
然后再,在我们执行命令的目录下面,多了一个ad文件
这些都是argparse解析命令行数据的功劳

2 argparse的使用

argparse的核心功能就3步
第一步 生成一个ArgumentParser这个类的实例对象parser
image
上面使用了prog等参数字段,具体意思后面会说到,这里也可以像之前的例子不加任何参数

第二步 在parser对象上添加参数名,这些参数就是我们命令行执行时要用到的
image
总的来说,添加参数名时,有3种类型的参数,positional arguments, options that accept values, and on/off flags

第三步 从parser对象上提取具体的参数数据,这些参数数据大部分是我们在命令行输入的数据
image
如上,通过parse_args()方法返回的对象加上参数名,我们就可以得到具体的参数数据

class argparse.ArgumentParser()

执行ArgumentParser()时,括号里接受下面这些参数来创建一个对象

  • prog - The name of the program (default: os.path.basename(sys.argv[0]))

  • usage - The string describing the program usage (default: generated from arguments added to parser)

  • description - Text to display before the argument help (by default, no text)

  • epilog - Text to display after the argument help (by default, no text)

  • parents - A list of ArgumentParser objects whose arguments should also be included

  • formatter_class - A class for customizing the help output

  • prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)

  • fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)

  • argument_default - The global default value for arguments (default: None)

  • conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)

  • add_help - Add a -h/--help option to the parser (default: True)

  • allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)

  • exit_on_error - Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True)

prog

这个字段会影响到program name的值,默认情况下,它是通过sys.argv[0]来取值的,即在命令行python后面紧邻的那一段文本中最后一部分,比如py文件的文件名
默认情况下是像这样
image

现在加上pro参数
image

image

usage

默认情况下 显示自定义的参数字段
image

加上usage后
image

image

description

添加该参数
image
image
如上,可看出默认情况下并没有相关数据的显示

还有很多其他参数,可具体查看官网

add_argument()

该方法也可以在括号中添加多个参数,如下

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.

  • action - The basic type of action to be taken when this argument is encountered at the command line.

  • nargs - The number of command-line arguments that should be consumed.

  • const - A constant value required by some action and nargs selections.

  • default - The value produced if the argument is absent from the command line and if it is absent from the namespace object.

  • type - The type to which the command-line argument should be converted.

  • choices - A sequence of the allowable values for the argument.

  • required - Whether or not the command-line option may be omitted (optionals only).

  • help - A brief description of what the argument does.

  • metavar - A name for the argument in usage messages.

  • dest - The name of the attribute to be added to the object returned by parse_args()

action

action参数值表示,我们在命令行中的参数数据应该被怎样处理,该参数默认值是store
action='store. 这是默认的处理方式,可以不用故意写出来,默认就是这样

action='store_const'
image

image
如上,未输入p2参数,p2的值被设为const的值,sore_const就是该参数的值为const的值
注意,这种情况下我们不能在命令行指定p2的值

'store_true' and 'store_false'
和action='store_const'类似
image

image

append
image

'count'
image
没有看懂到底有啥作用,好像就是统计参数字段出现的次数

未完待续

标签:default,argparse,python,argument,--,参数,命令行,action
From: https://www.cnblogs.com/MyRecords/p/17442042.html

相关文章

  • Visual AssistX Version 10.9.2491 Cracked
    任何问题请反馈至邮箱:[email protected](随缘查看邮件)Anyporbs->[email protected]再次声明:本破解补丁仅供交流学习和研究使用,不可用于商业。如果您喜欢该程序和内容,请支持正版,购买注册,得到更好的正版服务。Notice:thispatcherisforcommunication,lear......
  • 点与圆的关系
    #include<iostream>#include<string>usingnamespacestd;classpoint{private: intx,y;public: voidsetx(inta) { x=a; } intgetx() { returnx; } voidsety(intb) { y=b; } intgety() { returny; }};classcircle{private: intr; pointcen......
  • CentOS Linux基础操作
    CentOSLinuxLinux基础操作ifconfig查看端口号ls查看当前文件夹下内容-a显示指定文件夹下隐藏文件-l以列表的方式显示该文件夹-h配合-l显示文件大小ll的本质是ls-l,只是ll是Linux的第三方插件,系统如果没有安装,会显示没有此命令。pw......
  • Codeforces Round 875 (Div. 2) A-D
    A.TwinPermutations题意:给出一个由[1,2,...,n]组成的数组a,构造另一个由[1,2,...,n]组成的数组b,使得a[1]+b[1]<=a[2]+b[2]<=...<=a[n]+b[n]Solution可以想到只要让他们全为n+1就行了,这样是一定有解的voidsolve(){ intn;cin>>n; for(inti=1;i<=n;i++) { cin>>a[i]; ......
  • SQL语句
    SQL语句分类:DQL:数据查询语言,用于对数据进行查询DML:数据操作语言,对数据进行增加、修改、删除TPL:事务处理语言,对事务进行处理DDL:数据定义语言,进行数据库、表的管理等DCL:数据控制语言,进行授权与权限回收CCL:指针控制语言,通过控制指针完成表的操作数据库的增删改查是必须要掌......
  • Go语言学习之路
    【阶段1Go语言基础】Day01变量、字符串、运算符Day02Go语言流程控制、数组、切片、切片原理、map、Day03函数基础、错误处理、包管理Day04常用内置包Day05结构体Day06文件I/O操作Day07接口Day08并发编程Day09网络编程Day10webrpc爬虫模板语法【阶段2Go......
  • cpp: State Pattern
     /*****************************************************************//***\fileGold.h*\briefStatePattern状态模式C++14*2023年5月29日涂聚文GeovinDuVisualStudio2022edit.*\authorgeovindu*\dateMay2023************************......
  • 5.29
    今天Java考试代码如下packageservlet;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importmodel.PageBean;i......
  • vs 控制台输出
    void__cdeclOutputDebugPrintf(constchar*format,...){va_listvlArgs;char*strBuffer=(char*)GlobalAlloc(GPTR,4096);va_start(vlArgs,format);//_vsnprintf(strBuffer,4096-1,format,vlArgs);intsize=strlen(strBuffer)-1;......
  • ConcurrentHashMap
    引言HashMap在我们日常的开发中使用频率最高的一个工具类之一,然而使用HashMap最大的问题之一就是它是线程不安全的,如果我们想要线程安全,这时候就可以选择使用ConcurrentHashMap,ConcurrentHashMap和HashMap的功能是基本一样的,ConcurrentHashMap是HashMap的线程安全版......