$ ls ~yifei/notes/

Python 使用 argparse 处理命令行参数

Posted on:

Last modified:

基本用法

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
print(args.verbosity)

两种不同的参数模式,positionaloptional arguments,区别有点像 argskwargs.

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. store/store_const/store_true/append/count
nargs - The number of command-line arguments that should be consumed. N/?/*/+
const - A constant value required by some action and nargs selections.
default - The value produced if the argument is absent from the command line.
type - The type to which the command-line argument should be converted.
choices - A container of the allowable values for the argument. a list
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().

subcommand

一些比较复杂的命令行程序会分成许多子命令,比如 git 和 kubectl 等。argparse 也支持添加子命令, 不过有一些需要注意的地方。

parser = argparse.ArgumentParser()
# 一定要添加 dest 参数,这样才能读到用户使用的子命令
subparsers = parser.add_subparsers(dest="command")

install_parser = subparsres.add_parser("install")
install_parsre.add_argument("-d", "--dev", help="dev")

args = parser.parse_args()

if args.command == "install":
    ...

参考

  1. https://stackoverflow.com/questions/4575747/get-selected-subcommand-with-argparse
WeChat Qr Code

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.

友情链接: MySQL 教程站