argparse python模块的文档虽然非常棒,但对于我这个初学者来说,现在还难以理解。我不需要在命令行上做数学运算,也不需要在屏幕上修改格式行或更改选项字符。我想做的就是“如果arg是A,做这个,如果B做那个,如果以上都没有显示帮助并退出”。


当前回答

使用argparse和修改'-h'/ '——help'开关来显示你自己的个人代码帮助指令的一个非常简单的方法是将默认帮助设置为False,你也可以添加尽可能多的额外的.add_arguments:

import argparse

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('-h', '--help', action='help',
                help='To run this script please provide two arguments')
parser.parse_args()

执行命令python test.py -h

输出:

usage: test.py [-h]

optional arguments:
  -h, --help  To run this script please provide two arguments

其他回答

也可以使用plac (argparse的包装器)。

作为奖励,它生成整洁的帮助说明-见下文。

示例脚本:

#!/usr/bin/env python3
def main(
    arg: ('Argument with two possible values', 'positional', None, None, ['A', 'B'])
):
    """General help for application"""
    if arg == 'A':
        print("Argument has value A")
    elif arg == 'B':
        print("Argument has value B")

if __name__ == '__main__':
    import plac
    plac.call(main)

示例输出:

没有提供参数- example.py:

usage: example.py [-h] {A,B}
example.py: error: the following arguments are required: arg

提供了意外的参数- example.py

usage: example.py [-h] {A,B}
example.py: error: argument arg: invalid choice: 'C' (choose from 'A', 'B')

提供正确的参数- example.py

Argument has value A

完整帮助菜单(自动生成)- example.py -h:

usage: example.py [-h] {A,B}

General help for application

positional arguments:
  {A,B}       Argument with two possible values

optional arguments:
  -h, --help  show this help message and exit

简短说明:

实参的名称通常等于形参名称(arg)。

arg参数后的元组注释的含义如下:

描述(有两个可能值的参数) 参数类型- 'flag', 'option'或'positional' (positional)之一 缩写(无) 参数值的类型-例如。float, string (None) 限制选项集(['A', 'B'])

文档:

要了解更多关于使用placa的知识,请查看它的伟大文档:

Plac:解析命令行的简单方法

以下是我在学习项目中想到的,主要感谢@DMH…

演示代码:

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--flag', action='store_true', default=False)  # can 'store_false' for no-xxx flags
    parser.add_argument('-r', '--reqd', required=True)
    parser.add_argument('-o', '--opt', default='fallback')
    parser.add_argument('arg', nargs='*') # use '+' for 1 or more args (instead of 0 or more)
    parsed = parser.parse_args()
    # NOTE: args with '-' have it replaced with '_'
    print('Result:',  vars(parsed))
    print('parsed.reqd:', parsed.reqd)

if __name__ == "__main__":
    main()

这可能已经发展,可以在线使用:command-line.py

脚本对代码进行测试:command-line-demo.sh

注意Python HOWTOs中的Argparse教程。它从最基本的例子开始,比如这个:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)

然后发展到不那么基本的。

这里有一个预定义选项的例子,就像问的那样:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

这是另一个总结介绍,受这篇文章的启发。

import argparse

# define functions, classes, etc.

# executes when your script is called from the command-line
if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    #
    # define each option with: parser.add_argument
    #
    args = parser.parse_args() # automatically looks at sys.argv
    #
    # access results with: args.argumentName
    #

参数由以下组合定义:

parser.add_argument( 'name', options... )              # positional argument
parser.add_argument( '-x', options... )                # single-char flag
parser.add_argument( '-x', '--long-name', options... ) # flag with long name

常见的选项有:

help: description for this arg when --help is used. default: default value if the arg is omitted. type: if you expect a float or int (otherwise is str). dest: give a different name to a flag (e.g. '-x', '--long-name', dest='longName'). Note: by default --long-name is accessed with args.long_name action: for special handling of certain arguments store_true, store_false: for boolean args '--foo', action='store_true' => args.foo == True store_const: to be used with option const '--foo', action='store_const', const=42 => args.foo == 42 count: for repeated options, as in ./myscript.py -vv '-v', action='count' => args.v == 2 append: for repeated options, as in ./myscript.py --foo 1 --foo 2 '--foo', action='append' => args.foo == ['1', '2'] required: if a flag is required, or a positional argument is not. nargs: for a flag to capture N args ./myscript.py --foo a b => args.foo = ['a', 'b'] choices: to restrict possible inputs (specify as list of strings, or ints if type=int).

我对原问题的理解是双重的。首先,就最简单的argparse示例而言,我很惊讶在这里没有看到它。当然,为了简单起见,它也都是头顶上的,只有很少的电力,但它可能会让你开始。

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()

if args.a == 'magic.name':
    print 'You nailed it!'

但是这个位置参数现在是必需的。如果在调用此程序时省略它,则会得到关于缺少参数的错误。这就引出了原问题的第二部分。Matt Wilkie似乎想要一个没有命名标签(——option标签)的可选参数。我的建议是将上面的代码修改如下:

...
parser.add_argument("a", nargs='?', default="check_string_for_empty")
...
if args.a == 'check_string_for_empty':
    print 'I can tell that no argument was given and I can deal with that here.'
elif args.a == 'magic.name':
    print 'You nailed it!'
else:
    print args.a

也许有一个更优雅的解决方案,但这是可行的,而且是极简主义的。