# -*- coding:utf-8 -*-
import argparse
'''
@Author: weifg1@lenovo.com
@Create date: 2019.05.30
@Description: 使用argparse模块,该模块可用于命令行解析
@procedure: 1 、创建解析 2、添加参数 3、解析参数
'''
# 创建解析
parser = argparse.ArgumentParser(description='Study argparse.')
# 添加参数
parser.add_argument("name", type=str, default='Tom', dest='Name', choices=['Tom', 'Marry'])
parser.add_argument("-o", "--other", type=str, dest='other', help="other Information", required=False,nargs='*')
'''
每一个参数都需要单独设置,例如:需要两个参数便需要添加两次add_argument方法。
被添加的参数分为两种类型,positional arguments and optional arguments。通过'-'进行区分,参数变量前置‘-’或‘--’的为optional argments,其他的为posional argments 。
其中,
positional arguments 引入时可以不设置参数名,但必须有序设计。
optional arguments 引入时必须设置参数名, 参数具体数值设置可以无序。
optional arguments 中'-'与'--'可以同时设置。
参数设定:
1、name or flags(列表)
2、action 命令行参数操作
store 存参数的值
store_const 存const关键字指定的值,
store_true/store_false 存True/False
append 值追加到list中
append_const 根据const参数指定类型进行添加
count 统计参数出现次数
help
version
default
type 参数类型
choice:出现时需要指定type类型
dest:参数别名
require:是否为必须参数,默认True
nargs: 接受参数个数,具体值、?、'*' 接受0个或者多个参数、+
'''
# 解析参数
args = parser.parse_args()
#args.参数 显示参数值
print(args.name)
print(args.o)
python学习系列 argparse
最新推荐文章于 2025-05-13 08:17:47 发布