python 命令行參数解析
本文是从我还有一个博客转载过来的,欢迎大家点击进去看一下,帮我添加点人气^_^
选择模块
依据python參考手冊的提示,optparse 已经废弃,应使用 argparse
教程
概念
argparse 模块使用 add_argument 来加入可选的命令行參数,原型例如以下:
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are: name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
action - The basic type of action to be taken when this argument is encountered at the command line.
nargs - The number of command-line arguments that should be consumed.
const - A constant value required by some action and nargs selections.
default - The value produced if the argument is absent from the command line.
type - The type to which the command-line argument should be converted.
choices - A container of the allowable values for the argument.
required - Whether or not the command-line option may be omitted (optionals only).
help - A brief description of what the argument does.
metavar - A name for the argument in usage messages.
dest - The name of the attribute to be added to the object returned by parse_args().
上面的说明事实上不用看,直接看演示样例好了:
只想展示一些信息
# -*- coding: utf-8 -*-
"""
argparse tester
"""
import argparse parser = argparse.ArgumentParser(description='argparse tester') parser.add_argument("-v", "--verbose", help="increase output verbosity",
action="store_true") args = parser.parse_args() if args.verbose:
print "hello world"
它会输出例如以下:
$ python t.py
$ python t.py -v
hello world
$ python t.py -h
usage: t.py [-h] [-v] argparse tester optional arguments:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
这里 -v 是这个选项的简写。--verbose 是完整拼法,都是能够的
help 是帮助信息。不解释了
args = parse_args() 会返回一个命名空间,仅仅要你加入了一个可选项,比方 verbose。它就会把 verbose 加到 args 里去,就能够直接通过 args.verbose 訪问。
假设你想给它起个别名,就须要在 add_argument 里加多一个參数 dest='vb'
这样你就能够通过 args.vb 来訪问它了。
action="store_true" 表示该选项不须要接收參数,直接设定 args.verbose = True,
当然假设你不指定 -v。那么 args.verbose 就是 False
但假设你把 action="store_true" 去掉,你就必须给 -v 指定一个值。比方 -v 1
做个求和程序
# -*- coding: utf-8 -*-
"""
argparse tester
""" import argparse parser = argparse.ArgumentParser(description='argparse tester') parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
parser.add_argument('numbers', type=int, help="numbers to calculate", nargs='+')
parser.add_argument('-s', '--sum', help="sum all numbers", action='store_true', default=True) args = parser.parse_args() print "Input:", args.numbers
print "Result:"
results = args.numbers if args.verbose:
print "hello world" if args.sum:
results = sum(args.numbers)
print "tSum:tt%s" % results
输出例如以下:
[pan@pan-pc test]$ python t2.py -h
usage: t2.py [-h] [-v] [-s] numbers [numbers ...] argparse tester positional arguments:
numbers numbers to calculate optional arguments:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
-s, --sum sum all numbers
[pan@pan-pc test]$ python t2.py 1 2 3 -s
Input: [1, 2, 3]
Result:
Sum: 6
注意到这此可选项 numbers 不再加上 “-” 前缀了。由于这个是位置选项
假设把 nargs="+" 去掉,则仅仅能输入一个数字。由于它指定了number 选项的值个数
假设把 type=int 去掉。则 args.numbers 就是一个字符串。而不会自己主动转换为整数
注意到 --sum 选项的最后还加上了 default=True。意思是即使你不在命令行中指定 -s,它也会默认被设置为 True
仅仅能2选1的可选项
# -*- coding: utf-8 -*-
"""
argparse tester
""" import argparse parser = argparse.ArgumentParser(description='argparse tester')
#group = parser.add_mutually_exclusive_group() parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
parser.add_argument('numbers', type=int, help="numbers to calculate", nargs='+')
parser.add_argument('-s', '--sum', help="sum all numbers", action='store_true', default=True) parser.add_argument('-f', '--format', choices=['int', 'float'], help='choose result format', default='int') args = parser.parse_args() print "Input:", args.numbers
print "Result:"
results = args.numbers if args.verbose:
print "hello world" if args.format == 'int':
format = '%d'
else:
format = '%f' if args.sum:
results = sum(args.numbers)
print 'tsum:tt%s' % (format % results)
输出例如以下:
[pan@pan-pc test]$ python t2.py 1 2 3 -f float
Input: [1, 2, 3]
Result:
sum: 6.000000
[pan@pan-pc test]$ python t2.py 1 2 3 -f double
usage: t2.py [-h] [-v] [-s] [-f {int,float}] numbers [numbers ...]
t2.py: error: argument -f/--format: invalid choice: 'double' (choose from 'int', 'float')
在加入选项 -f 时,传入了 choices=['int', 'float'] 參数。表示该选项仅仅能从 int 或 float 中2选1
python 命令行參数解析的更多相关文章
- python命令行參数解析实例
闲言少述,直接上代码 #!/usr/bin/env python # # import json import getopt, sys def usage(): print sys.argv[ ...
- Python命令行參数大全
-b : 当转换数组为字符串时提出警告.比方str(bytes_instance), str(bytearray_instance). -B : 当导入.py[co]文 ...
- 第8章2节《MonkeyRunner源代码剖析》MonkeyRunner启动执行过程-解析处理命令行參数
MonkeyRunnerStarter是MonkeyRunner启动时的入口类,由于它里面包括了main方法.它的整个启动过程主要做了以下几件事情: 解析用户启动MonkeyRunner时从命令行传输 ...
- 命令行參数选项处理:getopt()及getopt_long()函数使用
在执行某个程序的时候,我们通常使用命令行參数来进行配置其行为.命令行选项和參数控制 UNIX 程序,告知它们怎样动作. 当 gcc的程序启动代码调用我们的入口函数 main(int argc ...
- Rust 1.7.0 处理命令行參数
std是 Rust 标准函数库: env 模块提供了处理环境函数. 在使用标准函数库的时候,使用 use 导入对应的 module . 一.直接输出 use std::env; fn main(){ ...
- VS2010中使用命令行參数
在Linux下编程习惯了使用命令行參数,故使用VS2010时也尝试了一下. 新建项目,c++编敲代码例如以下: #include<iostream> #include<fstream ...
- Python命令行选项參数解析策略
概述 在Python的项目开发过程中,我们有时须要为程序提供一些能够通过命令行进行调用的接口.只是,并非直接使用 command + 当前文件 就ok的,我们须要对其设置可选的各种各样的操作类型.所以 ...
- python命令行解析模块--argparse
python命令行解析模块--argparse 目录 简介 详解ArgumentParser方法 详解add_argument方法 参考文档: https://www.jianshu.com/p/aa ...
- Python命令行参数解析模块getopt使用实例
Python命令行参数解析模块getopt使用实例 这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参 ...
随机推荐
- BZOJ 4385 单调队列
思路: 对于每一个r 要找最小的符合条件的l最优 这时候就要找在这个区间中 d长度的和的最大值 用单调队列更新就好了 //By SiriusRen #include <cstdio> #i ...
- spring-cloud导入eclipse时,@slf4j注解为什么找不到log变量
原因是缺少插件Lomboz. Lomboz是一个基于LGPL的开源J2EE综合开发环境的Eclipse插件,对编码,发布,测试,以及debug等各个软件开发的生命周期提供支持,支持JSP,EJB等.L ...
- noip 2018 day1 T1 铺设道路 贪心
Code: #include<cstdio> using namespace std; int main() { int last=0,ans=0; int n;scanf("% ...
- @Mapper 和 @MapperScan 区别
1.@Mapper : 为了使接口被其他类引用,需要使用@Mapper注解,这种方式要求每一个mapper类都需要添加此注解,麻烦. package com.example.demo.dao; imp ...
- 【Henu ACM Round #13 E】Spy Syndrome 2
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 对m个串建立一棵字典树. 然后对主串. 尝试从第一个位置开始.在字典树中尝试匹配 如果匹配到了位置i 就再从位置i+1开始尝试匹配 ...
- C# 对Excel操作时,单元格值的读取
一.Range中Value与Value2的区别 当range("A1:B10")设置为 Currency (货币)和 Date (日期.日期时间)数据类型时,range2将返回对应 ...
- 手动脱FSG壳实战
作者:Fly2015 对于FSG壳.之前没有接触过是第一次接触.这次拿来脱壳的程序仍然是吾爱破解论坛破解培训的作业3的程序.对于这个壳折腾了一会儿,后来还是被搞定了. 1.查壳 首先对该程序(吾爱破解 ...
- java基本的语法
Java语言发展史 课程大纲: Java语言发展史: 1.sun公司1995年推出,2009年Oracle公司收购sun: 下载: 1.到Oracle官网下载 Java体系与特点 课程大纲: J ...
- JavaFX 一 出生新手村(阅读小规则)
我就不讲IDE怎么装的,网上有的是,我仅仅是说说我学习过程中遇到的,该注意的东西 1.JavaFX刚開始出是基于脚本script开发的语言,所以网上会有流传比較多关于script的JavaFX,对于被 ...
- elasticsearch index 之 create index(二)
创建索引需要创建索引并且更新集群index matedata,这一过程在MetaDataCreateIndexService的createIndex方法中完成.这里会提交一个高优先级,AckedClu ...