python 运行时传参_Python argparse的用法(运行时动态传参)

1. argparse介绍

是python的一个命令行解析包,用于编写可读性非常好的程序

2.基本用法

eg:

#导包

import argparse

#创建paser对象

parser = argparse.ArgumentParser()

#传参

parser.add_argument('-s','--show',action='store_true',help="you want show the result or not")

#创建读取对象

args=parser.parse_args()

#读取参数

isShow=args.show

3.positional arguments(必选参数)

调用

python ***.py xxx

eg:

#传参

parser.add_argument("echo")

#取参

x=args.echo

4. optional arguments(可选参数)

调用

python ***.py -s 123

或者

python ***.py --show 123

eg:

parser.add_argument('-s','--show',help="you want show the result or not")

x=args.show

5.action='store_true'

调用

python ***.py -s #代表show的值为true

或者

python ***.py #代表show的值为false

eg:

parser.add_argument('-s','--show',action='store_true',help="you want show the result or not")

isShow=args.show

6. 类型 type

默认的参数类型为str,如果要进行数学计算,需要对参数进行解析后进行类型转换。

eg:

parser.add_argument('x', type=int, help="the base")

x=args.x

7. 可选值choices=[]

限定其取值范围为[xx,yy,zz,...]

parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], help="increase output verbosity")

8.显示help信息

python xxx.py -h 或者 python xxx.py --help

9.默认参数

defalut

parser.add_argument("-v", "--verbosity", type=int, default=1, help="increase output verbosity")

如果内容有帮助到您,希望大家多多点赞+收藏+关注!!!

经常会在知乎中分享自己的学习笔记,和大家一起学习进步!!!

有问题大家可以在评论区打出,一定及时给大家回复!!!

笔记链接:有道云笔记​note.youdao.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值