Python argparse的例子?

时间:2014-01-04 16:37:16

标签: python python-3.x argparse

我正在尝试学习argparse以便在我的程序中使用它,语法应该是这样的:

-a --aLong <String> <String>
-b --bLong <String> <String> <Integer>
-c --cLong <String>
-h --help

我有这段代码:

#!/usr/bin/env python
#coding: utf-8

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Lorem Ipsum')
    parser.add_argument('-a','--aLong', help='Lorem Ipsum', required=False)
    parser.add_argument('-b','--bLong', help='Lorem Ipsum', required=False)
    parser.add_argument('-c','--cLong', help='Lorem Ipsum', required=False)
    parser.add_argument('-h','--help', help='Lorem Ipsum', required=False)
    parser.parse_args()

问题是,我在官方文档中看过,看过YouTube视频等,但我无法理解如何确定“主要参数”的“子参数”的数量?

示例:myApp.py -b Foobar 9000,如何设置-b必须有两个“子参数”,如何获取值Foobar9000

另一个疑问,我知道我可以设置一个参数为required,但我想让我的程序只在至少一个参数传递时执行,提到的四个。

也许这是一个愚蠢的问题,但对不起,我无法理解,希望有人在这里有“老师的力量”来解释它。

2 个答案:

答案 0 :(得分:5)

import argparse

# Use nargs to specify how many arguments an option should take.
ap = argparse.ArgumentParser()
ap.add_argument('-a', nargs=2)
ap.add_argument('-b', nargs=3)
ap.add_argument('-c', nargs=1)

# An illustration of how access the arguments.
opts = ap.parse_args('-a A1 A2 -b B1 B2 B3 -c C1'.split())

print(opts)
print(opts.a)
print(opts.b)
print(opts.c)

# To require that at least one option be supplied (-a, -b, or -c)
# you have to write your own logic. For example:
opts = ap.parse_args([])
if not any([opts.a, opts.b, opts.c]):
    ap.print_usage()
    quit()

print("This won't run.")

答案 1 :(得分:2)

关键是要定义一个必需的互斥组。

import argparse

# Use nargs to specify how many arguments an option should take.
ap = argparse.ArgumentParser()
group = ap.add_mutually_exclusive_group(required=True)
group.add_argument('-a', nargs=2)
group.add_argument('-b', nargs=3)
group.add_argument('-c', nargs=1)


# Grab the opts from argv
opts = ap.parse_args()

# This line will not be reached if none of a/b/c are specified.
# Usage/help will be printed instead.

print(opts)
print(opts.a)
print(opts.b)
print(opts.c)