美文网首页TECH
Python | argparse

Python | argparse

作者: shwzhao | 来源:发表于2022-07-03 16:41 被阅读0次

参考:
博客园 | Python解析命令行读取参数 -- argparse模块
公众号 | 生信菜鸟团 | python:argparse用于命令行参数解析
公众号 | Python 命令行之旅 —— 深入 argparse (一)
公众号 | Python 命令行之旅 —— 深入 argparse (二)
公众号 | Python 基础(二十一):argparse 模块
argparse — 解析命令参数和选项

简单学习了一下,够自己用就行了。

$ cat test.py
#!python3

import argparse

def create_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--version", action="version", version="0.0.1")
    parser.add_argument("-i", "--infile") # 以 - 开头,如果不以 - 开头,视为位置参数
    parser.add_argument("-o", "--outfile", default="outfile")

    sub_parser = parser.add_subparsers()
    sub_seq = sub_parser.add_parser("seq") # 设置子命令 seq
    sub_seq.add_argument("-w", "--width", type=int)

    sub_grep = sub_parser.add_parser("grep") # 设置子命令 grep
    sub_grep.add_argument("-f", "--file", nargs="*")

    return parser

if __name__ == "__main__":
    parser = create_parser()
    args = parser.parse_args()
    print(vars(args))
    print(args.infile)
$ python3 test.py -v
0.0.1
$ python3 test.py -i test_file
{'infile': 'test_file', 'outfile': 'outfile'}
test_file
$ python3 test.py -h
usage: test.py [-h] [-v] [-i INFILE] [-o OUTFILE] {seq,grep} ...

positional arguments:
  {seq,grep}

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  -i INFILE, --infile INFILE
  -o OUTFILE, --outfile OUTFILE
$ python3 test.py grep -h
usage: test.py grep [-h] [-f [FILE [FILE ...]]]

optional arguments:
  -h, --help            show this help message and exit
  -f [FILE [FILE ...]], --file [FILE [FILE ...]]
  1. parser = argparse.ArgumentParser(): 添加描述信息,可为空
  • usage: 使用,自动生成
  • description: 描述信息
  • epilogprog......
  1. sub_parser = parser.add_subparsers(): 添加子命令
    sub_seq = sub_parser.add_parser("seq")
  1. parser.add_argument(): 添加选项
  • help: 参数描述
  • version: 版本号
  • default: 默认值
  • choices: 可选参数范围
  • required: 是否一定要设置该选项
    required=True
    required=False
  • type: 指定参数类型,默认str
    type=int/float/bool: 整数/浮点数/逻辑型
    type=open
    type=limit
  • nargs: 选项后参数个数
    nargs=3: 要求3个参数
    nargs="*": 允许0或多个参数
    nargs="?": 要求0或1个参数
    nargs="+": 要求至少1个参数
  • const: 指定了选项,但没指定参数时,取const设定的值,而不取default的值。在nargs="?"action="store_const"时有用。
  • action: 接收命令行参数后如何处理
    action="store": 保存参数值,默认
    action="store_const": 设定选项后,将参数的值解析为const的值
    action="store_true": 设定选项后,将参数值自动解析为True
    action="store_false": 设定选项后,将参数值自动解析为False
    action="append": 存储为一个列表,多次使用一个选项时使用
    action="append_const": 存储为一个列表,将const的值追加到列表
    action="count": 统计一个选项出现的次数
  • destmatavar...... 不会,先不管
  1. parser.parse_args(): 解析

  2. parser.print_help(): 打印描述信息

还有很多,比如选项冲突......

相关文章

网友评论

    本文标题:Python | argparse

    本文链接:https://www.haomeiwen.com/subject/ytyevrtx.html