您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python中argparse库的基本使用(示例)

2026/2/8 7:55:07发布20次查看
本篇文章给大家带来的内容是关于python中argparse库的基本使用(示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
基本使用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库的基本使用(示例)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product