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
# 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'))
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
...
parser.add_argument("a", nargs='?', default="check_string_for_empty")
...
if args.a == 'check_string_for_empty':
print 'I can tell that no argument was given and I can deal with that here.'
elif args.a == 'magic.name':
print 'You nailed it!'
else:
print args.a
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
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()
#!/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)
示例输出:
# EYZ1 # EYZ0:
usage: example.py [-h] {A,B}
example.py: error: the following arguments are required: arg
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
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
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
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))
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))
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
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')
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
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')
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')
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')
$ python3 test.py
help
$ python3 test.py -A
do this
$ python3 test.py -B
do that
$ python3 test.py -C
usage: test.py [-h] [-A] [-B]
test.py: error: unrecognized arguments: -C
对于最初的请求(如果A ....),我将使用argv来解决它,而不是使用argparse:
import sys
if len(sys.argv)==2:
if sys.argv[1] == 'A':
print('do this')
elif sys.argv[1] == 'B':
print('do that')
else:
print('help')
else:
print('help')