python 命令行參数解析

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

ImPyy

选择模块

依据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

输出例如以下:

[[email protected] 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
[[email protected] 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)

输出例如以下:

[[email protected] test]$ python t2.py 1 2 3 -f float
Input: [1, 2, 3]
Result:
    sum:        6.000000
[[email protected] 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

时间: 2024-07-30 10:19:39

python 命令行參数解析的相关文章

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

MonkeyRunnerStarter是MonkeyRunner启动时的入口类,由于它里面包括了main方法.它的整个启动过程主要做了以下几件事情: 解析用户启动MonkeyRunner时从命令行传输进来的參数: 由于MonkeyRunner须要依据指定的參数才干做事情,比方输入的一个须要执行的脚本. 假设确实不知道不论什么參数的话它就会进入MonkeyRunner的交互模式,事实上就是Jythong的交互模式,让用户能够边写代码边执行 启动AndroidDebugBridge: 事实上就是启动

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

在执行某个程序的时候,我们通常使用命令行參数来进行配置其行为.命令行选项和參数控制 UNIX 程序,告知它们怎样动作. 当 gcc的程序启动代码调用我们的入口函数 main(int argc,char *argv[]) 时,已经对命令行进行了处理.argc 參数包括程序參数的个数,而 argv 包括指向这些參数的指针数组. 程序的參数能够分为三种:选项.选项的关联值,非选项參数. 比如: $gcc getopt_test.c -o testopt getopt_test.c是非选项參数.-o是选

Rust 1.7.0 处理命令行參数

std是 Rust 标准函数库: env 模块提供了处理环境函数. 在使用标准函数库的时候,使用 use 导入对应的 module . 一.直接输出 use std::env; fn main(){ for argument in env::args() { println!("*** args = {}", argument); } } $cargo run 12 and 78 Running `target/debug/attribute_test 12 and 78` *** a

【Python】python 命令行参数模块解析 定义

# coding=UTF-8 # see: https://www.cnblogs.com/victorwu/p/5762665.html # python2.7 可用 import argparse parser = argparse.ArgumentParser(description = '支持的命令描述信息') parser.add_argument('--ver', '-v', help = '测试的参数') parser.add_argument('-p','--port', typ

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

概述 在Python的项目开发过程中,我们有时须要为程序提供一些能够通过命令行进行调用的接口.只是,并非直接使用 command + 当前文件 就ok的,我们须要对其设置可选的各种各样的操作类型.所以,这样的情况下我们就有必要对传入的參数进行解析操作. 以下就此问题提出几种不同的解决策略.希望于你故意. 版权说明 著作权归作者全部. 商业转载请联系作者获得授权,非商业转载请注明出处. 作者:Coding-Naga 发表日期: 2016年3月18日 链接:http://blog.csdn.net/

【Python】Python获取命令行參数

有时候须要用同一个Python程序在不同的时间来处理不同的文件,此时假设老是要到Python程序中去改动输入.输出文件名称,就太麻烦了.而通过Python获取命令行參数就方便多了.以下是我写得一个小程序,希望对大家有所帮助. 比方以下一个程序test.py是通过接受命令行两个參数.并打印出这两个參数. import sys #需导入sys模块 print sys.argv[1], sys.argv[2] #打印出从命令行接受的两个參数 Linux下执行:python test.py Hello

用什么库写 Python 命令行程序?看这一篇就够了

作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Article 一.前言 在近半年的 Python 命令行旅程中,我们依次学习了 argparse.docopt.click 和 fire 库的特点和用法,逐步了解到 Python 命令行库的设计哲学与演变. 本文作为本次旅程的终点,希望从一个更高的视角对这些库进行横向对比,总结它们的异同点和使用场景,以期在应对不同

Python命令行参数

Python命令行参数: -d 在解析时显示调试信息 -O 生成优化代码 ( .pyo 文件 ) -S 启动时不引入查找Python路径的位置 -v 输出Python版本号 -X 从 1.6版本之后基于内建的异常(仅仅用于字符串)已过时. -c cmd 执行 Python 脚本,并将运行结果作为 cmd 字符串. file 在给定的python文件执行python脚本.

让你如绅士般基于描述编写 Python 命令行工具的开源项目:docopt

作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Article 一.前言 在本系列前面四篇文章中,我们介绍了 argparse 的方方面面.它无疑是强大的,但使用方式上略显麻烦.需要先设置解析器,再定义参数,再解析命令行,最后实现业务逻辑. 而今天要介绍的 docopt 则是站在一个全新的视角来审视命令行.你可曾想过,一个命令行程序的帮助信息其实已然包含了这个命令