getopt模块可以用来解析运行时的输入参数。它是标准库模块,无需使用pip install安装。

getopt()函数介绍

getopt模块中主要使用的函数为getopt(),其函数原型为:
def getopt(args, shortopts, longopts = [])

各个参数含义如下:

  • args一般是sys.argv[1:]sys.argv[0]为文件名,不属于参数。
  • shortopts短参数,短参数表示以一个字母表示的参数。如果短参数有值,要求在该短参数后接一个冒号':'
  • longopts长参数,长参数表示以一个单词表示的参数。如果长参数有值,要求在该长参数后接一个等号'='

下面给出getopt的函数定义:

def getopt(args, shortopts, longopts = []):"""getopt(args, options[, long_options]) -> opts, argsParses command line options and parameter list.  args is theargument list to be parsed, without the leading reference to therunning program.  Typically, this means "sys.argv[1:]".  shortoptsis the string of option letters that the script wants torecognize, with options that require an argument followed by acolon (i.e., the same format that Unix getopt() uses).  Ifspecified, longopts is a list of strings with the names of thelong options which should be supported.  The leading '--'characters should not be included in the option name.  Optionswhich require an argument should be followed by an equal sign('=').The return value consists of two elements: the first is a list of(option, value) pairs; the second is the list of program argumentsleft after the option list was stripped (this is a trailing sliceof the first argument).  Each option-and-value pair returned hasthe option as its first element, prefixed with a hyphen (e.g.,'-x'), and the option argument as its second element, or an emptystring if the option has no argument.  The options occur in thelist in the same order in which they were found, thus allowingmultiple occurrences.  Long and short options may be mixed."""opts = []if type(longopts) == type(""):longopts = [longopts]else:longopts = list(longopts)while args and args[0].startswith('-') and args[0] != '-':if args[0] == '--':args = args[1:]breakif args[0].startswith('--'):opts, args = do_longs(opts, args[0][2:], longopts, args[1:])else:opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])return opts, args

函数的返回值是为(opts, args)的元组:

  • opts是表示最终解析出的属性值对(option, value)元组的list;
  • args是未被解析出的剩余参数组成的list,实际调用时该参数一般不处理。

参数的传递格式

短参数传递格式

短参数都以’-'开头:

不带参数时:
-p
带参数时:
-p 6379
-p '6379'
-p6379

长参数传递格式:

长参数都以’–'(两个\-)开头:

不带参数时:
--port
带参数时:
--port=6379 (左右无空格,否则识别失败)
--port 6379

一定要注意,短参数的-后面与长参数的’–'后都无空格。长参数==左右都无空格。

实际案例

redis-server.py如下所示:

from getopt import getopt
import sysopts, args = getopt(sys.argv[1:], 'i:p:s', ['ip=', 'port=', 'single'])
print(opts, args)for option, value in opts:if option in ('-i', '--ip'):print(f'ip = {value}')elif option in ('-p', '--port'):print(f'port = {value}')elif option in ('-s', '--single'):print('run in single')

运行如下测试用例:

> python redis-server.py
> [] []
> python redis-server.py -i 127.0.0.1 -p 6379 -s
> [('-i', '127.0.0.1'), ('-p', '6379'), ('-s', '')] []
> ip = 127.0.0.1
> port = 6379
> run in single
> python redis-server.py --ip=127.0.0.1 --port=6379 -s
> [('--ip', '127.0.0.1'), ('--port', '6379'), ('-s', '')] []
> ip = 127.0.0.1
> port = 6379
> run in single
> python redis-server.py -i 127.0.0.1 --port=6379 -s
> [('-i', '127.0.0.1'), ('--port', '6379'), ('-s', '')] []
> ip = 127.0.0.1
> port = 6379
> run in single
> python redis-server.py --ip=127.0.0.1 -p 6379 -s
> [('--ip', '127.0.0.1'), ('-p', '6379'), ('-s', '')] []
> ip = 127.0.0.1
> port = 6379
> run in single

上面这些都是正确的调用方式,下面给出几种错误的调用方式:

> python redis-server.py i 127.0.0.1 # i前不加-
> [] ['i', '127.0.0.1']
> python redis-server.py -ip=127.0.0.1 # --ip少写一个-
> [('-i', 'p=127.0.0.1')] []
> ip = p=127.0.0.1
> python redis-server.py --ip =127.0.0.1 # =左有空格
> [('-i', 'p')] ['=127.0.0.1']
> ip = p
> python redis-server.py --ip= 127.0.0.1 # =右有空格
> [('-i', 'p=')] ['127.0.0.1']
> ip = p=
> python redis-server.py --ip = 127.0.0.1 # =左右有空格
> [('--ip', '=')] ['127.0.0.1']
> ip = =

参考资料

getopt在Python中的使用
python - getopt()

Python 参数解析(getopt模块)相关推荐

  1. [转]Python 命令行参数和getopt模块详解

    FROM : http://www.tuicool.com/articles/jaqQvq 有时候我们需要写一些脚本处理一些任务,这时候往往需要提供一些命令行参数,根据不同参数进行不同的处理,在Pyt ...

  2. python 命令行参数处理 getopt模块详解

    有时候我们需要写一些脚本处理一些任务,这时候往往需要提供一些命令行参数,根据不同参数进行不同的处理,在Python里,命令行的参数和C语言很类似(因为标准Python是用C语言实现的).在C语言里,m ...

  3. python参数解析模块_Python系列教程(三十七):参数解析模块argparse

    使用python写出的脚本在运行的时候,是可以传递参数的,一般会使用sys.argv[]来接收用户传的参数.但是如果要实现类似于linux命令的,比如'ls -l -t /etc/'这种比较复杂的选项 ...

  4. windows 下 Python的命令行参数解析 argparse模块 的使用

        argparse模块是Python内置的参数解析模块,相较于传统的 sys.argv 来说,其功能更加的强大,操作也更灵活. ArgumentParser类创建时的参数如下: prog - 程 ...

  5. python argparse(参数解析)模块学习(二)

    转载自:http://www.cnblogs.com/fireflow/p/4841389.html(我去..没转载功能,ctrl + c 和 ctrl + v 得来的,格式有点问题,可去原版看看) ...

  6. python 参数解析_python的函数对参数解析分析

    以下转自其它博客.觉得总结得太好了,所以拿来自己参考一下. python中函数参数的传递是通过赋值来传递的. 函数参数的使用又有俩个方面值得注意: 1.函数参数是如何定义的 2.在调用函数的过程中参数 ...

  7. python 参数解析器_Python中最好用的命令行参数解析工具

    接下来只剩下 argparse 这一神器,它几乎能满足我对命令解析器的所有需求.它支持解析一参数多值,可以自动生成help命令和帮助文档,支持子解析器,支持限制参数取值范围等等功能. 身为老司机,还是 ...

  8. python 参数解析器_Python参数解析器,在h之前引发异常

    我不知道为什么会这样.我的理解是用户至少有机会在执行默认操作之前使用-h.import os, sys, argparse class argument_parser(): # call on all ...

  9. Python中最好用的命令行参数解析工具

    Python 做为一个脚本语言,可以很方便地写各种工具.当你在服务端要运行一个工具或服务时,输入参数似乎是一种硬需(当然你也可以通过配置文件来实现). 如果要以命令行执行,那你需要解析一个命令行参数解 ...

  10. Python之命令行参数解析

    Python 做为一个脚本语言,可以很方便地写各种工具.当你在服务端要运行一个工具或服务时,输入参数似乎是一种硬需(当然你也可以通过配置文件来实现). 如果要以命令行执行,那你需要解析一个命令行参数解 ...

最新文章

  1. 碰撞检测碰撞Java简单游戏开发之碰撞检测
  2. 新冠肺炎数据里学到的四个数据分析和机器学习知识
  3. PLSQL developer 连接不上64位Oracle 的解决方法
  4. C#中获取当前时间字符串给文件命名防止重复
  5. 从 Vue 1.x 迁移 — Vue.js
  6. sigmastarSSD201/SSD202 github上开源了!
  7. C++喜欢收录和反链都保持增长的态势
  8. python小城市创业好项目_小城市创业好项目有哪些?
  9. virtual.lab motion用表达式控制载荷
  10. linux stoping redis,redis的cluster集群模式shell一键启动/停止/重启/清缓存脚本
  11. WebLogic 12c 中压缩传输的配置
  12. 俄罗斯网络间谍被指攻击斯洛伐克政府长达数月
  13. 【angularjs】【学习心得】路由继续研究篇
  14. 数组的最长递减子序列java_求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}...
  15. 计算机丢失disrupt,disrupt造句
  16. 【草图大师Sketchup插件开发】画盒子工具
  17. 使用Raspberry Pi搭建迅雷离线下载机
  18. 未来第五代计算机的发展方向,走进新时代 从五代酷睿看未来电脑发展
  19. 简谈RSS——巧用Feed43制作自定义RSS源
  20. 敏捷其实很简单(9)Scrum Master的七种武器之离别钩霸王枪箱子

热门文章

  1. [概率论]-随机变量
  2. 2017上半年软考 第十二章 重要知识点
  3. rabbitmq 安装 windows
  4. 使用windows Phone 集成横幅广告教程
  5. 设计模式之Prototype(原型)
  6. 6.Docker技术入门与实战 --- Docker数据管理
  7. 41.Linux/Unix 系统编程手册(下) -- 共享库基础
  8. 4.高性能MySQL --- Schema与数据类型优化
  9. 开源的Web Service测试工具
  10. [2019上海网络赛F题]Rhyme scheme