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


当前回答

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

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).

其他回答

以下是我在学习项目中想到的,主要感谢@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

我浏览了所有的例子和答案,但在某种程度上,它们并没有满足我的需求。所以我会给她列出一个我需要更多帮助的场景,我希望这能更好地解释这个想法。

最初的问题

我需要开发一个工具,它得到一个文件来处理它,它需要一些可选的配置文件来配置工具。

所以我需要的是以下内容

mytool.py file.text -config config-file.json

解决方案

下面是解决方案代码

import argparse

def main():
    parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
    parser.add_argument('filename', help="Input file either text, image or video")
    # parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
    # parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
    parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

    args = parser.parse_args()
    
    filename = args.filename
    configfile = args.config_file

    print("The file to be processed is", filename)
    print("The config file is", configfile)

    if args.debug:
        print("Debug mode enabled")
    else:
        print("Debug mode disabled")

    print("and all arguments are: ", args)

if __name__ == '__main__':
    main()

我将在多个增强中展示解决方案,以展示其思想

第一轮:列出论点

将所有输入列为强制输入,因此第二个参数为

parser.add_argument('config_file', help="a JSON file to load the initial configuration ")

当我们获得该工具的帮助命令时,会发现以下结果

(base) > python .\argparser_example.py -h
usage: argparser_example.py [-h] filename config_file

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename     Input file either text, image or video
  config_file  a JSON file to load the initial configuration

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

当我像下面这样执行它时

(base) > python .\argparser_example.py filename.txt configfile.json

结果将是

The file to be processed is filename.txt
The config file is configfile.json
and all arguments are:  Namespace(config_file='configfile.json', filename='filename.txt')

但是配置文件应该是可选的,我从参数中删除了它

(base) > python .\argparser_example.py filename.txt

结果将是:

usage: argparser_example.py [-h] filename config_file
argparser_example.py: error: the following arguments are required: c

也就是说我们的工具有问题

第二轮:优化

因此,为了使它成为可选的,我修改了程序如下

    parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)

帮助的结果应该是

usage: argparser_example.py [-h] [-c CONFIG] filename

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename              Input file either text, image or video

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        a JSON file to load the initial configuration

所以当我执行程序时

(base) > python .\argparser_example.py filename.txt

结果将是

The file to be processed is filename.txt
The config file is configFile.json
and all arguments are:  Namespace(config_file='configFile.json', filename='filename.txt')

有这样的论点

(base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json

结果将是

The file to be processed is filename.txt
The config file is anotherConfig.json
and all arguments are:  Namespace(config_file='anotherConfig.json', filename='filename.txt')

第三轮:增强

要将标志名从——config_file更改为——config,同时保持变量名不变,我们修改代码,包括dest='config_file',如下所示:

parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')

命令是

(base) > python .\argparser_example.py filename.txt --config anotherConfig.json

为了增加对调试模式标志的支持,我们需要在参数中添加一个标志来支持布尔调试标志。为了实现它,我添加了以下内容:

    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

工具命令如下:

(carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug

结果将是

The file to be processed is image.jpg
The config file is imageConfig,json
Debug mode enabled
and all arguments are:  Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')

Matt正在询问argparse中的位置参数,我同意Python文档在这方面是缺乏的。在大约20多页的文章中,没有一个完整的例子同时展示了解析和使用位置参数。

这里的其他答案都没有显示位置参数的完整示例,所以这里有一个完整的示例:

# tested with python 2.7.1
import argparse

parser = argparse.ArgumentParser(description="An argparse example")

parser.add_argument('action', help='The action to take (e.g. install, remove, etc.)')
parser.add_argument('foo-bar', help='Hyphens are cumbersome in positional arguments')

args = parser.parse_args()

if args.action == "install":
    print("You asked for installation")
else:
    print("You asked for something other than installation")

# The following do not work:
# print(args.foo-bar)
# print(args.foo_bar)

# But this works:
print(getattr(args, 'foo-bar'))

让我困惑的是argparse将命名参数“——foo-bar”转换为“foo_bar”,但是名为“foo-bar”的位置参数仍然是“foo-bar”,这使得在程序中如何使用它变得不那么明显。

注意示例末尾的两行——这两行都不能获取foo-bar位置参数的值。第一个显然是错误的(它是一个算术表达式。Foo - bar),但第二个也不行:

AttributeError: 'Namespace' object has no attribute 'foo_bar'

如果希望使用foo-bar属性,必须使用getattr,如示例的最后一行所示。疯狂的是,如果你试图使用dest=foo_bar将属性名更改为更容易访问的名称,你会得到一个非常奇怪的错误消息:

ValueError: dest supplied twice for positional argument

下面是上面例子的运行方式:

$ python test.py
usage: test.py [-h] action foo-bar
test.py: error: too few arguments

$ python test.py -h
usage: test.py [-h] action foo-bar

An argparse example

positional arguments:
  action      The action to take (e.g. install, remove, etc.)
  foo-bar     Hyphens are cumbersome in positional arguments

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

$ python test.py install foo
You asked for installation
foo

由于你没有澄清参数“A”和“B”是位置的还是可选的,我将两者混合。

默认情况下,位置参数是必需的。如果没有给出一个将抛出'Few arguments given'这不是可选参数的情况下,以他们的名字。默认情况下,此程序将接受一个数字并返回其方框,如果使用cube选项,则将返回其方框。

import argparse
parser = argparse.ArgumentParser('number-game')
parser.add_argument(
    "number",
    type=int,
    help="enter a number"
   )
parser.add_argument(
   "-c", "--choice",
   choices=['square','cube'],
   help="choose what you need to do with the number"
)

# all the results will be parsed by the parser and stored in args
args = parser.parse_args()

# if square is selected return the square, same for cube 
if args.c == 'square':
    print("{} is the result".format(args.number**2))
elif args.c == 'cube':
    print("{} is the result".format(args.number**3))
else:
    print("{} is not changed".format(args.number))

使用

$python3 script.py 4 -c square
16

这里的可选参数是有值的,如果你只是想把它当作一个标志来使用,你也可以。因此,通过对square使用-s,对cube使用-c,我们可以通过添加action = "store_true"来改变行为。仅在使用时才更改为true。

parser.add_argument(
    "-s", "--square",
    help="returns the square of number",
    action="store_true"
    )
parser.add_argument(
    "-c", "--cube",
    help="returns the cube of number",
    action="store_true"
    )

所以条件块可以更改为,

if args.s:
    print("{} is the result".format(args.number**2))
elif args.c:
    print("{} is the result".format(args.number**3))
else:
    print("{} is not changed".format(args.number))

使用

$python3 script.py 4 -c
64

使用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