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


当前回答

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

其他回答

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

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

这是一个新手,但是将Python与Powershell结合起来并使用这个模板,灵感来自深入而伟大的Python命令行参数-真正的Python

在init_argparse()中可以做很多事情,这里我只介绍最简单的场景。

import argparse use if __name__ == "__main__": main() pattern to execute from terminal parse arguments within the main() function that has no parameters as all define a init_argparse() function create a parser object by calling argparse.ArgumentParser() declare one or more argumnent with parser.add_argument("--<long_param_name>") return parser parse args by creating an args object by calling parser.parse_args() define a function proper with param1, param2, ... call function_proper with params being assigned as attributes of an args object e.g. function_proper(param1=args.param1, param2=args.param2) within a shell call the module with named arguments: e.g. python foobar.py --param1="foo" --param2=="bar"

#file: foobar.py
import argparse

def function_proper(param1, param2):
    #CODE...

def init_argparse() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    parser.add_argument("--param1")
    parser.add_argument("--param2")
    return parser


def main() -> None:
    parser = init_argparse()
    args = parser.parse_args()
    function_proper(param1=args.param1, param2=args.param2)


if __name__ == "__main__":
    main()
>>> python .\foobar.py --param1="foo" --param2=="bar"

补充一下其他人已经说过的话:

我通常喜欢使用'dest'参数指定变量名,然后使用'globals().update()'将这些变量放在全局命名空间中。

用法:

$ python script.py -i "Hello, World!"

代码:

...
parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
globals().update(vars(parser.parse_args()))
...
print(inputted_variable) # Prints "Hello, World!"