Python 命令行参数

Python 命令行参数

  • 1、sys 库 sys.argv 获取参数
  • 2、getopt 模块解析带`-`参数
    • 2.1 短参数shortopts
      • 2.1.1 无短参数
      • 2.1.2 短参数`h`无值
      • 2.1.3 短参数`h`有值
      • 2.1.4 多个短参数`h:v`
    • 2.2 长参数longopts
      • 2.2.1 长参数无值
      • 2.2.2 长参数有值
    • 2.3 有空格字符串值

1、sys 库 sys.argv 获取参数

sys 库 sys.argv 来获取命令行参数:

  • sys.argv 是命令行参数列表。

  • len(sys.argv) 是命令行参数个数。


注:sys.argv[0] 表示脚本名。

# ! /usr/bin/env python
# coding=utf-8import sysif __name__ == '__main__':args = sys.argvprint('参数个数为:', len(args), '个参数。')print('参数列表:', str(args))

在这里插入图片描述

2、getopt 模块解析带-参数

getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式 - 和长选项模式 --

getopt(args, shortopts, longopts = [])

  • args: 是用来解析的命令行字符串,通常为sys.argv[1:]属于必传参数

  • shortopts : 是用来匹配命令行中的短参数,为字符串类型,options 后的冒号 : 表示如果设置该选项,必须有附加的参数,否则就不附加参数。属于必传参数

  • longopts: 是用来匹配命令行中的长参数,为列表类型,long_options 后的等号 = 表示该选项必须有附加的参数,不带等号表示该选项不附加参数。

  • 该方法返回值由两个元素组成: 第一个opts是 (option, value) 元组的列表,用来存放解析好的参数和值。 第二个args是参数列表,用来存放不匹配 - 或 - - 的命令行参数。
    (Exception getopt.GetoptError 在没有找到参数列表,或选项的需要的参数为空时会触发该异常。)

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

2.1 短参数shortopts

2.1.1 无短参数

此时getoptshortopts应传入"",必传参数,即getopt.getopt(args, "")

# ! /usr/bin/env python
# coding=utf-8import sys, getoptif __name__ == '__main__':try:opts, args = getopt.getopt(sys.argv[1:], "")except getopt.GetoptError:print(' Exception getopt.GetoptError ')sys.exit(2)print("opts=" + str(opts))print("args=" + str(args))

在这里插入图片描述

2.1.2 短参数h无值

此时getoptshortopts应传入"h",必传参数,即getopt.getopt(args, "h")

# ! /usr/bin/env python
# coding=utf-8import sys, getoptif __name__ == '__main__':try:opts, args = getopt.getopt(sys.argv[1:], "h")except getopt.GetoptError:print(' Exception getopt.GetoptError ')sys.exit(2)print("opts=" + str(opts))print("args=" + str(args))

在这里插入图片描述

2.1.3 短参数h有值

此时getoptshortopts应传入"h:",必传参数,即getopt.getopt(args, "h:")

# ! /usr/bin/env python
# coding=utf-8import sys, getoptif __name__ == '__main__':try:opts, args = getopt.getopt(sys.argv[1:], "h:")except getopt.GetoptError:print(' Exception getopt.GetoptError ')sys.exit(2)print("opts=" + str(opts))print("args=" + str(args))

在这里插入图片描述

2.1.4 多个短参数h:v

此时getoptshortopts应传入"h:v",必传参数,即getopt.getopt(sys.argv[1:], "h:v")

# ! /usr/bin/env python
# coding=utf-8import sys, getoptif __name__ == '__main__':try:opts, args = getopt.getopt(sys.argv[1:], "h:v")except getopt.GetoptError:print(' Exception getopt.GetoptError ')sys.exit(2)print("opts=" + str(opts))print("args=" + str(args))

在这里插入图片描述

2.2 长参数longopts

2.2.1 长参数无值

此时getoptshortopts应传入["help"],即getopt.getopt(args, "",["help"])

# ! /usr/bin/env python
# coding=utf-8import sys, getoptif __name__ == '__main__':try:opts, args = getopt.getopt(sys.argv[1:], "", ["help"])except getopt.GetoptError:print(' Exception getopt.GetoptError ')sys.exit(2)print("opts=" + str(opts))print("args=" + str(args))

在这里插入图片描述

2.2.2 长参数有值

此时getoptshortopts应传入["help="],即getopt.getopt(args, "",["help="])

# ! /usr/bin/env python
# coding=utf-8import sys, getoptif __name__ == '__main__':try:opts, args = getopt.getopt(sys.argv[1:], "", ["help="])except getopt.GetoptError:print(' Exception getopt.GetoptError ')sys.exit(2)print("opts=" + str(opts))print("args=" + str(args))

在这里插入图片描述

2.3 有空格字符串值

中间有空格的字符串,则需要使用""/''将其括起

# ! /usr/bin/env python
# coding=utf-8import sys, getoptif __name__ == '__main__':try:opts, args = getopt.getopt(sys.argv[1:], "h:v:", ["help=", "version="])except getopt.GetoptError:print(' Exception getopt.GetoptError ')sys.exit(2)print("opts=" + str(opts))print("args=" + str(args))

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/4357.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode189.轮转数组

⭐️ 题目描述 leetcode链接:轮转数组 ⭕️ C代码实现: /*[1,2,3,4,5,6,7], k 3 , numsSize 7思路:1. 逆置 (0) - (numsSize - k - 1) 下标的元素- [4 , 3 , 2 , 1 , 5 , 6 , 7]2. 逆置 (numsSize - k) - (numsSize - 1) 下标的元素- [3 …

海思平台图像的IQ调试

目录 1.何为ISP何为IQ调试 1.1、ISP概念 1.2、在哪里做ISP 1.3、何为IQ 1.4、总结 2.海思MPP中ISP的实现框架 2.1、官方文档 2.2、sample中ISP相关部分 2.3、sensor注册内部细节 2.4、ISP注册内部细节 3.IQ调试相关的概念 3.1、黑电平 3.2、镜头阴影矫正 3.3、坏点…

从源码全面解析 dubbo 服务端服务调用的来龙去脉

👏作者简介:大家好,我是爱敲代码的小黄,独角兽企业的Java开发工程师,CSDN博客专家,阿里云专家博主📕系列专栏:Java设计模式、Spring源码系列、Netty源码系列、Kafka源码系列、JUC源码…

如何删除Git仓库中的敏感文件及其历史记录

本文主要介绍如何使用 git filter-branch 命令删除 Git 仓库中的敏感文件及其历史记录。在 Git 中,我们通常会将敏感信息(如密码、私钥等)存储在 .gitignore 文件中,以防止这些信息被意外提交到仓库。有时候,因为疏忽或私有仓库转公开仓库&am…

RocketMQ --- 高级篇

一、高级功能 1.1、消息存储 分布式队列因为有高可靠性的要求,所以数据要进行持久化存储。 消息生成者发送消息MQ收到消息,将消息进行持久化,在存储中新增一条记录返回ACK给生产者MQ push 消息给对应的消费者,然后等待消费者返回…

Python 使用 NetworkX

Python 使用 NetworkX 说明:本篇文章主要讲述 python 使用 networkx 绘制有向图; 1. 介绍&安装 NetworkX 是一个用于创建、操作和研究复杂网络的 Python 库。它提供了丰富的功能,可以帮助你创建、分析和可视化各种类型的网络&#xff…

基于OpenCV的人脸对齐步骤详解及源码实现

目录 1. 前言2. 人脸对齐基本原理与步骤3. 人脸对齐代码实现 1. 前言 在做人脸识别的时候,前期的数据处理过程通常会遇到一个问题,需要将各种人脸从不同尺寸的图像中截取出来,再进行人脸对齐操作:即将人脸截取出来并将倾斜的人脸…

76、基于STM32单片机车牌识别摄像头图像处理扫描设计(程序+原理图+PCB源文件+相关资料+参考PPT+元器件清单等)

单片机主芯片选择方案 方案一:AT89C51是美国ATMEL公司生产的低电压,高性能CMOS型8位单片机,器件采用ATMEL公司的高密度、非易失性存储技术生产,兼容标准MCS-51指令系统,片内置通用8位中央处理器(CPU)和Flash存储单元&a…

使用Streamlit和Matplotlib创建交互式折线图

大家好,本文将介绍使用Streamlit和Matplotlib创建一个用户友好的数据可视化Web应用程序。该应用程序允许上传CSV文件,并为任何选定列生成折线图。 构建Streamlit应用程序 在本文中,我们将指导完成创建此应用程序的步骤。无论你是专家还是刚刚…

CTF安全竞赛介绍

目录 一、赛事简介 二、CTF方向简介 1.Web(Web安全) (1)简介 (2)涉及主要知识 2.MISC(安全杂项) (1)介绍 (2)涉及主要知识 3…

设计模式之行为型模式

本文已收录于专栏 《设计模式》 目录 概念说明大话设计模式行为型模式 各模式详解第一组观察者模式(Observer Pattern)模板方法模式(Template Method Pattern)命令模式(Command Pattern)状态模式&#xff0…

智能指针+拷贝构造+vector容器+多态引起的bug

今天在调试一段代码的时候,VC编译提示: error C2280: “T485CommCtrlPara::T485CommCtrlPara(const T485CommCtrlPara &)”: 尝试引用已删除的函数 函数执行部分如下: 看意思是这个pComm485Pro已经消亡了,后续push_back到ve…