3

我在使用 argparse 时遇到了一些问题。我想有一组可以在命令行上定义的名称,这将影响程序的行为。我尝试了以下代码段:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("allon", action='store_true', default = False,
                    help="Toggles all output pins to ON.")
parser.add_argument("alloff",action='store_true',
                    help="Toggles all output pins to OFF.")
parser.add_argument("cont", action='store_true',
                    help="Toggles all output pins continously on and off.")
args = parser.parse_args()

if args.allon:
   do_allon()
elif args.alloff:
    do_alloff()
....

但代码的行为超出了预期。我不想对这些选项使用'--',因为我想调用我的代码git status(没有前导'--')。

首先,如果我在没有参数的情况下调用代码,所有参数都设置为 True,而如果没有给出,我希望它们设置为 False。预期的行为如下:调用时

python code.py

我想要allon, alloff并被cont设置为False, 而当调用为

python code.py alloff

我想要alloncont成为False而被alloff设置为True

其次,当我打电话给例如python code.py allon我得到

code.py: error: unrecognized arguments: allon

我根本不明白。我知道如何使用 optparse,但是非常感谢您对 argparse 的帮助以使上述代码段正常工作。

谢谢亚历克斯

PS if 循环只是教育性的,实际上并没有以这种方式实现。

4

4 回答 4

6

当您看到像git status,git commit等命令模式时,我们正在谈论子命令。要创建子命令, argparse 允许您使用sub-parsers,它们本质上就像主解析器(采用命令行开关等)。

像这样定义它们:

import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='sub-command help')

allon_parser = subparsers.add_parser('allon',
    help='Toggles all output pins to ON.')
allon_parser.set_defaults(func=do_allon)

alloff_parser = subparsers.add_parser('alloff',
    help="Toggles all output pins to OFF.")
alloff_parser.set_defaults(func=do_alloff)

cont_parser = subparsers.add_parser('cont',
    help="Toggles all output pins continously on and off.")
cont_parser.set_defaults(func=do_cont)

args = parser.parse_args()
# Call the associated `func` function
args.func()

我已将一个函数与每个子解析器 ( set_defaults(func=...)) 相关联,因此该args结构将具有func指向已定义函数之一的属性。我们只需要调用它。

输出--help

usage: PROG [-h] {cont,alloff,allon} ...

positional arguments:
  {cont,alloff,allon}  sub-command help
    allon              Toggles all output pins to ON.
    alloff             Toggles all output pins to OFF.
    cont               Toggles all output pins continously on and off.

optional arguments:
  -h, --help           show this help message and exit
于 2012-09-20T07:33:51.903 回答
1

选项通常使用-短参数(1 个字符)的前导或--长参数的前导来指定。

因此,你应该给你的可选参数两个前导破折号:

import argparse
parser = argparse.ArgumentParser()
# Note that `default=False` is unnecessary since it's implied by `store_true`.
parser.add_argument("--allon", action='store_true',
                    help="Toggles all output pins to ON.")
parser.add_argument("--alloff",action='store_true',
                    help="Toggles all output pins to OFF.")
parser.add_argument("--cont", action='store_true',
                    help="Toggles all output pins continously on and off.")
args = parser.parse_args()

if args.allon:
    do_allon()
elif args.alloff:
    do_alloff()
....
于 2012-09-20T06:46:17.427 回答
1

如果你想让你的函数的第一个参数是强制性的,并限制可用的选择,这样做:

import argparse
parser = argparse.ArgumentParser()

parser.add_argument("action", action="store", choices=['allon', 'alloff', 'cont'])

args = parser.parse_args()

if args.action == 'allon':
    print 'allon'
elif args.action == 'alloff':
    print 'alloff'

示例用法:

$ python req_argparse.py allon
allon
$ python req_argparse.py alloff
alloff
$ python req_argparse.py nope
usage: req_argparse.py [-h] {allon,alloff,cont}
req_argparse.py: error: argument action: invalid choice: 'nope' (choose from 'allon', 'alloff', 'cont')
于 2012-09-20T07:00:52.360 回答
0

When options in argparseare optional flags, they should start with --like so:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--allon", action='store_true', default = False,
                    help="Toggles all output pins to ON.")
parser.add_argument("--alloff",action='store_true',
                    help="Toggles all output pins to OFF.")
parser.add_argument("--cont", action='store_true',
                    help="Toggles all output pins continously on and off.")
args = parser.parse_args()

如果我们再添加代码:

print args.allon, args.alloff, args.cont

我们可以证明您的程序将具有所需的行为:

$ python test.py
False False False
$ python test.py --allon
True False False
$ python test.py --alloff
False True False
$ python test.py --cont
False False True
$ python test.py --allon --alloff --cont
True True True

ETA:如果您想要一个与 git 的status, add,commit等等效的子命令,那么可选标志将不是实现它的正确方法。您应该改用argparse 的add_subparsers功能

于 2012-09-20T06:45:31.047 回答