JCh*_*ris 11 python argparse python-3.x
我正在尝试学习argparse以便在我的程序中使用它,语法应该是这样的:
-a --aLong <String> <String>
-b --bLong <String> <String> <Integer>
-c --cLong <String>
-h --help
Run Code Online (Sandbox Code Playgroud)
我有这个代码:
#!/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()
Run Code Online (Sandbox Code Playgroud)
问题是,我在官方文档中看过,看过YouTube视频等,但我无法理解如何确定"主要参数"的"子参数"的数量?
示例:myApp.py -b Foobar 9000,如何设置-b必须有两个"子参数",如何获取值,Foobar和9000?
还有一个疑问,我知道我可以设置一个参数是否存在required,但是我想让我的程序只在至少传递一个参数时才执行,所提到的四个参数中的任何一个.
也许这是一个愚蠢的问题,但对不起,我无法理解,希望有人在这里有"老师的力量"来解释它.
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.")
Run Code Online (Sandbox Code Playgroud)