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


当前回答

也可以使用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:解析命令行的简单方法

其他回答

作为现有答案的补充,如果你足够懒惰,可以使用称为protoargs的代码生成工具。它从配置生成参数解析器。对于python,它使用argparse。

配置可选A和B:

syntax = "proto2";
message protoargs
{
    optional string A     = 1; // A param description
    optional string B     = 2; // B param description
}//protoargs

配置所需的A和B:

syntax = "proto2";
message protoargs
{
    required string A     = 1; // A param description
    required string B     = 2; // B param description
}//protoargs

位置A和B的构型:

syntax = "proto2";
message protoargs
{
    required string A     = 1; // A param description
    required string B     = 2; // B param description
}//protoargs
message protoargs_links
{
}//protoargs_links

现在你要做的就是:

python ./protoargs.py -i test.proto -o . --py

并使用它(这里可以举其他例子):

import sys
import test_pa

class ArgsParser:
    program = "test"
    description = "Simple A and B parser test."

    def parse(self, argv):
        self.config = test_pa.parse(self.program, self.description, argv)

    def usage(self):
        return test_pa.usage(self.program, self.description)

if __name__ == "__main__":
    parser = ArgsParser()

    if len(sys.argv) == 1:
        print(parser.usage())
    else:
        parser.parse(sys.argv[1:])

        if parser.config.A:
            print(parser.config.A)

        if parser.config.B:
            print(parser.config.B)

如果你想要更多的改变配置,重新生成解析器,使用更新的parser.config。

UPD:正如规则中提到的,我必须指定这是我自己的项目

最简单的答案!

附注:编写argparse文档的人是愚蠢的

python代码:

import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--o_dct_fname',type=str)
parser.add_argument('--tp',type=str)
parser.add_argument('--new_res_set',type=int)
args = parser.parse_args()
o_dct_fname = args.o_dct_fname
tp = args.tp
new_res_set = args.new_res_set

运行代码

python produce_result.py --o_dct_fname o_dct --tp father_child --new_res_set 1

下面是我使用argparse(使用多个args)的方法:

parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())

Args将是一个包含参数的字典:

if args['foo'] == 'Hello':
    # code here

if args['bar'] == 'World':
    # code here

在您的情况下,只需添加一个参数。

也可以使用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