基本使用import argparse# 创建解析器parser = argparse.argumentparser(description = 'this is a test')parser.parse_args()
可以在shell中测试:
$ python test.py --help...
添加参数import argparseparser = argparse.argumentparser(description = 'this is a test')parser.add_argument(-p,--port,help='increase output port') # 定义了可选参数-p和--port,赋值后,其值保存在args.port中(其值都是保存在最后一个定义的参数中)args = parser.parse_args()print(args.echo)
使用时候:
$ python test.py -p 50或$ python test.py --port 50
指定类型我们也可以在添加参数的时候指定其类型。
import argparseparser = argparse.argumentparser(description = 'this is a test')parser.add_argument(square,help=display a given number,type=int) # 指定给square的参数为int类型
可选参数import argparseparser = argparse.argumentparser()parser.add_argument(-v, help=increase output verbosity)args = parser.parse_args()if args.v: print(v turned on)
使用:
$ python test.py -v any
以上就是python中argparse库的基本使用(示例)的详细内容。
