python读取命令行选项参数

Python中由三个内建的模块用于处理命令行参数:
第一个:getopt,只能简单的处理命令行参数

官网资料:https://docs.python.org/2/library/getopt.html#module-getopt
第二个:optparse,功能强大,易于使用,可以方便地生成标准的、符合Unix/Posix 规范的命令行说明。(Python2.7以后弃用,不会继续发展)
官网资料:https://docs.python.org/2/library/optparse.html
第三个:argparse,使其更加容易的编写用户友好的命令行接口。它所需的程序进程了参数定义,argparse将更好的解析sys.argv。同时argparse模块还能自动生成帮助及用户输入错误参数时的提示信息。

官网资料:https://docs.python.org/2/library/argparse.html#module-argparse

getopt

   在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能。目前常用的由短选项和长选项两种格式。短选项格式为"-"加上单个字母 选项,长选项为"--"加上一个单词。长格式实在Linux下引入的。许多Linux程序都支持这两种格式。在Python中提供了getopt模块很好 的实现了对着两种用法的支持,而且使用简单。

获取命令行参数

Python环境下可以使用sys模块得到命令行参数

import getopt
import sysprint(sys.argv)C:\Users\Administrator\>python 222.py -o t --help cmd file1 file2
['222.py', '-o', 't', '--help', 'cmd', 'file1', 'file2']# 由此可见,所有命令行参数以空格为分隔符,保存在sys.argv列表中,其中第一个为文件名

选项的写法要求:
短格式:"-"号后面要紧跟一个选项字母。如果还有此选项的附加参数,可以用空格分开,也可以不分开。长度任意,可以用引号。
例如:
-o 
-o "a b"
长格式:"--"号后面要跟一个单词。如果还有些选项的附加参数,后面要紧跟"=",再加上参数。"="号前后不能有空格。
例如:
--help=file1

如何使用getopt进行参数分析及处理?

第一步:导入sys,getopt模块
第二步:分析命令行参数
第三步:处理结果

import getopt
import sys# print(sys.argv)
def usage():print(
"""
Usage:sys.args[0] [option]
-h or --help:显示帮助信息
-m or --module:模块名称   例如:ansible all -m shell -a 'date'
-a or --args:模块对于的参数  例如:ansible all -m shell -a 'date'
-v or --version:显示版本
""")
if len(sys.argv) == 1:usage()sys.exit()try:opts, args = getopt.getopt(sys.argv[1:], "ho:m:a:", ["help", "output="])   # sys.argv[1:] 过滤掉第一个参数(它是脚本名称,不是参数的一部分)
except getopt.GetoptError:print("argv error,please input")# 使用短格式分析串“ho:m:a:”当一个选项只表示开关状态时,即后面不带任何参数时,在分析串中写入选项字符,例如:-h表示获取帮助信息,显示完成即可,不需任何参数当一个选项后面需要带附加参数时,在分析串中写入选项字符同时后面加一个“:”号,例如:-m表示指定模块名称,后面需加模块名称# 使用长格式分析串列表:["help", "output="]。
长格式串也可以有开关状态,即后面不跟"="号。如果跟一个等号则表示后面还应有一个参数。这个长格式表示"help"是一个开关选项;"output="则表示后面应该带一个参数。
# print(opts)
# print(args)
# 调用getopt函数。函数返回两个列表:opts和args。
# opts为分析出的格式信息,是一个两元组的列表。每个元素为:(选项串,附加参数)。如果没有附加参数则为空串''。
# args为不属于格式信息的剩余的命令行参数。
# 整个过程使用异常来包含,这样当分析出错时,就可以打印出使用信息来通知用户如何使用这个程序。# 以下部分即根据分析出的结果做相应的处理,并将处理结果返回给用户
for cmd, arg in opts:  # 使用一个循环,每次从opts中取出一个两元组,赋给两个变量。cmd保存选项参数,arg为附加参数。接着对取出的选项参数进行处理。if cmd in ("-h", "--help"):print("help info")sys.exit()elif cmd in ("-o", "--output"):output = argelif cmd in ("-m", "--module"):module_name = argelif cmd in ("-a", "--module_args"):module_args = argelif cmd in ("-v", "--version"):print("%s version 1.0" % sys.argv[0])

案例2:获取用户信息,生成配置信息

argparse

 argparse简介

   argparse是Python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。argparse模块的作用是用于解析 命 令行参数,例如python parseTest.py input.txt output.txt --user=name --port=8080。

argparse讲解

将以下代码保存为prog.py

import argparseparser = argparse.ArgumentParser(description='Process some integers.')   # 首先创建一个ArgumentParser对象
parser.add_argument('integers', metavar='N', type=int, nargs='+',           # 添加参数help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,help='sum the integers (default: find the max)')     # 添加--sum则返回所有数之和,否则返回列表中的最大值args = parser.parse_args()
print args.accumulate(args.integers)
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]Process some integers.positional arguments:N           an integer for the accumulatoroptional arguments:-h, --help  show this help message and exit--sum       sum the integers (default: find the max)# 输入正确的参数信息
$ python prog.py 1 2 3 4
4$ python prog.py 1 2 3 4 --sum
10# 输入错误的参数信息
$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'
ArgumentParser对象的参数
prog - The name of the program (default: sys.argv[0])
usage - The string describing the program usage (default: generated from arguments added to parser)
description - Text to display before the argument help (default: none)
epilog - Text to display after the argument help (default: none)
parents - A list of ArgumentParser objects whose arguments should also be included
formatter_class - A class for customizing the help output
prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)
fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)
argument_default - The global default value for arguments (default: None)
conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
add_help - Add a -h/–help option to the parser (default: True)
每个参数的详细说明:
prog:即运行程序的名称,默认取sys.argv[0]的值,可以修改为指定的名称
usage:指定usage信息的内容及格式,默认是根据你添加的信息自动生成的,可以自定义修改为指定的内容
description:这个程序的功能概述
epilog:在整个帮助信息最后添加的附加信息
parents:用于定义一些公共的信息供子类调用
formatter_class:整个信息的类定义,主要包含三个类,每个类的功能如下:
  • class argparse.RawDescriptionHelpFormatter # 如何显示文本描述
  • class argparse.RawTextHelpFormatter # 如何显示文本描述
  • class argparse.ArgumentDefaultsHelpFormatter # 自定添加参数信息
prefix_chars:自定义参数个前缀类型
fromfile_prefix_chars:指定文件替代命令行输入参数的方式
argument_default:
conflict_handler:检测是否存在相同的参数选项,不加该参数直接报错,添加该参数可以兼容(conflict_handler='resolve')
add_help:  设置是否显示帮助信息那表之类(默认显示)

 不设置该参数

 设置该参数

add_argument()方法    

格式: ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

  • 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().

实际案例讲解

# 基本认识,只有就基本框架
import argparseparser = argparse.ArgumentParser()
parser.parse_args()# 结果
C:\Users\Administrator\Desktop>python3 getopt_help.py -h
usage: getopt_help.py [-h]optional arguments:-h, --help  show this help message and exitC:\Users\Administrator\Desktop>python3 getopt_help.py foo
usage: getopt_help.py [-h]
getopt_help.py: error: unrecognized arguments: fooC:\Users\Administrator\Desktop>python3 getopt_help.py -f
usage: getopt_help.py [-h]
getopt_help.py: error: unrecognized arguments: -f# 结果分析
1)不给参数而运行这个程序,将不会得到任何结果
2)没有做任何特别设置,可以得到一个很简洁的帮助信息(第二三个例子)
3)无需人为设置--help参数,就能得到一个良好的帮助信息。但是若给其他参数(比如foo)就会产生一个错误。

其他

 if len(sys.argv) == 1:parser.print_help()sys.exit(1)

【python】python读取命令行选项参数相关推荐

  1. python 命令行参数-python实现读取命令行参数的方法

    本文实例讲述了python读取命令行参数的方法.分享给大家供大家参考.具体分析如下: 如果想对python脚本传参数,python中对应的argc, argv(c语言的命令行参数)是什么呢? 需要模块 ...

  2. linux 读取命令行输入参数,shell脚本读取文件+读取命令行参数+读取标准输入+变量赋值+输出到文件...

    读取url_list文件批量下载网页 url_list http://www.tianyancha.com/company/2412078287 http://www.4399.com/special ...

  3. python求两数之和的命令_python实现读取命令行参数的方法

    本文实例讲述了python读取命令行参数的方法.分享给大家供大家参考.具体分析如下: 如果想对python脚本传参数,python中对应的argc, argv(c语言的命令行参数)是什么呢? 需要模块 ...

  4. 下列不是python对文件的读操作方法_以下选项不是Python文件读操作

    以下选项不是Python文件读操作 答:readtext() Z检验可以用于单个率的检验. 答:对 中国大学MOOC: 在正常膝关节,胫骨围绕股骨从完全屈曲到完全伸直,沿股骨内侧髁的运动曲线是 答:先 ...

  5. 下列不是python对文件的读操作方法_以下选项不是Python文件读操作的是.

    以下选项不是Python文件读操作的是. 答:readtext() 沟通结束以后一定要 答:形成一个共同的协议 针对地下水的研究主要对象是饱和带内的地下水.() 答:√ 下列不是抗日民主根据地出版的报 ...

  6. linux下bash脚本常用的十个技巧:显示执行脚本花费的时间,在脚本退出时杀死后台运行的程序,在脚本退出时跳出循环,读取命令行参数来决定循环次数

    文章目录 1.显示执行脚本花费的时间 2.在脚本退出时杀死后台运行的程序 3.在脚本退出时跳出循环 4.读取命令行参数来决定循环次数 1.显示执行脚本花费的时间 网址:bash - How to ge ...

  7. python 答题卡识别_opencv+python机读卡识别(初级版)

    最近在进一步学习Python,在网上发现有使用opencv进行机读卡识别的, 就根据大神的文章,跟着学习,自己写了一个机读卡识别, 文章一:opencv+python机读卡识别整合版 文章二:pyth ...

  8. Python教程:命令行参数处理

    sys模块 sys模块代表了Python解释器,主要用于获取和Python解释器相关的信息,其中 sys.argv 可以获取命令行参数 在Python交互式解释器中可以先导入sys模块 import ...

  9. python中处理命令行参数命令getopt

    转自 http://andylin02.iteye.com/blog/845355 os下有个方法walk,非常的好用,用来生成一个generator.每次可以得到一个三元tupple,其中第一个为起 ...

  10. python是什么意思怎么读-python怎么读,python是什么意思

    python怎么读: 英[ˈpaɪθən] 美[ˈpaɪθɑːn] python是什么意思:中文就是蟒蛇的意思,一种脚本语言 ----------------------------- 小朋友们,欢迎 ...

最新文章

  1. 光荣与梦想 | XMove动作捕捉系统(一)
  2. echo 和 var_dump
  3. 大头贴计算机教程,美颜相机大头贴在哪里 教你怎么弄动漫大头贴
  4. 页面传值-laber
  5. Linux下dislocate命令用法,五个超酷Linux命令
  6. 新方法-根据上排给出十个数,在其下排填出对应的十个数
  7. Spring2..5整合Ehacahe
  8. Free Mybatis plugin
  9. 考研总分多少能去辽师_辽宁师范大学在职研究生统考分数到达到多少呢统考通过就会被录取吗...
  10. linux根目录下各文件的作用
  11. Java实现Excel数据导入数据库
  12. 等宽字体 Monospaced Font
  13. md5加密工具类(16位,32位,64位)
  14. 小功能--扫描二维码自动连接WiFi
  15. GitHub上README.md文件的图片大小尺寸
  16. 一款PHP版三合一收款码_附50多款模板源码
  17. 深度增强学习:走向通用人工智能之路
  18. 网站服务器怎么做防御?遇到攻击如何解决?
  19. Java根据多个文件URL打包成一个压缩包下载
  20. FastDFS清空数据及文件步骤

热门文章

  1. 易中天品汉代风云人物02: 冤死的晁错(下)
  2. endNote教程 -4-编辑参考文件格式
  3. 用the_excerpt处理中文文章字数限制的方法
  4. ptp输出内容包含什么_PTP 无线传输
  5. android 重力感应切换屏幕,Android 重力感应和屏幕旋转关系
  6. select update delete
  7. 基于51单片机的无线病床呼叫系统装置 proteus仿真原理图程序设计
  8. WEB漏洞攻防 -根据不同数据库类型之间的差异性进行注入
  9. python如何控制运行时间_Python控制函数运行时间
  10. 蒟蒻退役记————————————(3)