本文是从我还有一个博客转载过来的,欢迎大家点击进去看一下,帮我添加点人气^_^


选择模块

依据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 命令行參数解析的更多相关文章

  1. python命令行參数解析实例

    闲言少述,直接上代码 #!/usr/bin/env python # # import json import getopt, sys def usage():     print sys.argv[ ...

  2. Python命令行參数大全

      -b     :    当转换数组为字符串时提出警告.比方str(bytes_instance), str(bytearray_instance). -B     :    当导入.py[co]文 ...

  3. 第8章2节《MonkeyRunner源代码剖析》MonkeyRunner启动执行过程-解析处理命令行參数

    MonkeyRunnerStarter是MonkeyRunner启动时的入口类,由于它里面包括了main方法.它的整个启动过程主要做了以下几件事情: 解析用户启动MonkeyRunner时从命令行传输 ...

  4. 命令行參数选项处理:getopt()及getopt_long()函数使用

         在执行某个程序的时候,我们通常使用命令行參数来进行配置其行为.命令行选项和參数控制 UNIX 程序,告知它们怎样动作. 当 gcc的程序启动代码调用我们的入口函数 main(int argc ...

  5. Rust 1.7.0 处理命令行參数

    std是 Rust 标准函数库: env 模块提供了处理环境函数. 在使用标准函数库的时候,使用 use 导入对应的 module . 一.直接输出 use std::env; fn main(){ ...

  6. VS2010中使用命令行參数

    在Linux下编程习惯了使用命令行參数,故使用VS2010时也尝试了一下. 新建项目,c++编敲代码例如以下: #include<iostream> #include<fstream ...

  7. Python命令行选项參数解析策略

    概述 在Python的项目开发过程中,我们有时须要为程序提供一些能够通过命令行进行调用的接口.只是,并非直接使用 command + 当前文件 就ok的,我们须要对其设置可选的各种各样的操作类型.所以 ...

  8. python命令行解析模块--argparse

    python命令行解析模块--argparse 目录 简介 详解ArgumentParser方法 详解add_argument方法 参考文档: https://www.jianshu.com/p/aa ...

  9. Python命令行参数解析模块getopt使用实例

    Python命令行参数解析模块getopt使用实例 这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参 ...

随机推荐

  1. Android CardView卡片布局 标签: 控件

    CardView介绍 CardView是Android 5.0系统引入的控件,相当于FragmentLayout布局控件然后添加圆角及阴影的效果:CardView被包装为一种布局,并且经常在ListV ...

  2. Coderfroces 864 E. Fire(01背包+路径标记)

    E. Fire http://codeforces.com/problemset/problem/864/E Polycarp is in really serious trouble — his h ...

  3. Inter-process Communication (IPC)

    For Developers‎ > ‎Design Documents‎ > ‎ Inter-process Communication (IPC) 目录 1 Overview 1.1 I ...

  4. ES6学习笔记(二)变量的解构与赋值

    1.数组的解构赋值 1.1基本用法 ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring). 以前,为变量赋值,只能直接指定值. let a = 1 ...

  5. WPF 支持的多线程 UI 并不是线程安全的

    原文:WPF 支持的多线程 UI 并不是线程安全的 版权声明:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可.欢迎转载.使用.重新发布,但务必保留文章署名吕毅(包含链 ...

  6. SpringBoot @PathVariable 和 @requestParam区别

    1.若获取的入参的 参数 是下面这种形式 就使用 @requestParam 去获取 参数‘1’ /user?id=1 // url:xxx/user?id=1 @RequestMapping(&qu ...

  7. Linux局域网登陆响应时间过长

    在局域网中,使用ssh登陆到其他机器上时,有时会出现等待10s以上才能正常登陆的问题. 原因: Linux默认使用dns解析登陆IP,但是在局域网,并没有dns服务器,而且机器上也没有添加 IP与域名 ...

  8. ZOJ 2562 HDU 4228 反素数

    反素数: 对于不论什么正整数x,起约数的个数记做g(x).比如g(1)=1,g(6)=4. 假设某个正整数x满足:对于随意i(0<i<x),都有g(i)<g(x),则称x为反素数. ...

  9. ESP8266学习笔记4:ESP8266的SmartConfig

    今天花了将近一天的时间来研究ESP8266的SmartConfig功能,这个应该算是wifi云产品的标配.这篇文章先把SmartConfig操作一遍,我还写了还有一篇文章梳理了物理层的详细协议,点击这 ...

  10. worldpress 的 GPG 加密插件

    worldpress 的 GPG 加密插件资料来源 https://trog.qgl.org/wpgpg/这个插件的作用是,用GPG 加密worldpress 的输出内容,然后在chrome浏览器中上 ...