Python 命令行参数

news2024/9/30 19:30:29

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-8

import sys


if __name__ == '__main__':
    args = sys.argv
    print('参数个数为:', 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, args

   Parses command line options and parameter list.  args is the
   argument list to be parsed, without the leading reference to the
   running program.  Typically, this means "sys.argv[1:]".  shortopts
   is the string of option letters that the script wants to
   recognize, with options that require an argument followed by a
   colon (i.e., the same format that Unix getopt() uses).  If
   specified, longopts is a list of strings with the names of the
   long options which should be supported.  The leading '--'
   characters should not be included in the option name.  Options
   which 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 arguments
   left after the option list was stripped (this is a trailing slice
   of the first argument).  Each option-and-value pair returned has
   the option as its first element, prefixed with a hyphen (e.g.,
   '-x'), and the option argument as its second element, or an empty
   string if the option has no argument.  The options occur in the
   list in the same order in which they were found, thus allowing
   multiple 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:]
           break
       if 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-8

import sys, getopt


if __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-8

import sys, getopt


if __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-8

import sys, getopt


if __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-8

import sys, getopt


if __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-8

import sys, getopt


if __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-8

import sys, getopt


if __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-8

import sys, getopt


if __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.coloradmin.cn/o/711108.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Kubernetes核心概念汇总—调度、抢占和驱逐(Pod 调度就绪态)

Pod 一旦创建就被认为准备好进行调度。 Kubernetes 调度程序尽职尽责地寻找节点来放置所有待处理的 Pod。 然而,在实际环境中,会有一些 Pod 可能会长时间处于"缺少必要资源"状态。 这些 Pod 实际上以一种不必要的方式扰乱了调度器(…

Vue3 如何去开发安卓 或者 ios

Vue3 有没有一款好用的开发原生的工具 1.uniapp 我个人认为uniapp 适合开发小程序之类的,用这个去开发原生应用会存在一些问题 性能限制:由于 Uniapp 是通过中间层实现跨平台,应用在访问底层功能时可能存在性能损失。与原生开发相比&#xf…

【Linux】调试工具gdb

目录 前言 一、前情了解 二、gdb常用命令 1.基本指令 2.断点 3.调试过程 4.查看内容 前言 gdb是Linux环境下了一个调试工具,在代码运行出现问题时,我们可以通过它来进行调试,找出问题的所在。本文来带大家来了解一下gdb的使用方法。 …

单片机第一季:零基础1

目录 1,第一章 2,第二章 1,第一章 单片机是全球用量最大的CPU,是物联网节点设备主控CPU,单片机是其他物联网编程技术的基础,通过学习单片机学习编程语言、调试技巧、工具使用等; 51单片机最简…

【前端笔记】indexDB使用简单介绍

什么是indexDB? IndexedDB 是一种底层 API,用于在客户端存储大量的结构化数据(也包括文件/二进制大型对象(blobs))。该 API 使用索引实现对数据的高性能搜索。虽然 Web Storage 在存储较少量的数据很有用&…

chatgpt赋能python:如何用Python计算圆面积

如何用Python计算圆面积 介绍 圆是几何学中基本的图形之一,圆面积的计算是数学中的基础知识。使用Python编程语言可以快速、简便地计算圆的面积。本文将介绍如何使用Python编写圆面积计算器,并演示计算圆面积的步骤。无需高深的数学知识,只…

IPv6地址分类

一. 前言 IPv6地址分为单播地址,组播地址和任播地址。它们的地址详细分类和地址的范围如下图所示。 二. IPv6地址分类 1. 全球单播地址 类似于IPv4的公网地址,由前缀,子网ID和接口标识组成。 2. 链路本地地址 只能在连接到同一个本地链路的节…

《空指针》Optional解决链式调用NPE问题

Optional解决链式调用NPE问题 1.map() public class Main {public static void main(String[] args) {Person person new Person();Info personInfo new Info();int result;// 1.PersonInfo 为空person.setPersonInfo(null);result Optional.ofNullable(person).map(Person…

cpp-httplib

安装 cpp-httplib gitee链接: https://gitee.com/yuanfeng1897/cpp-httplib?_fromgitee_searchv0.7.15版本链接: https://gitee.com/yuanfeng1897/cpp-httplib/tree/v0.7.15把httplib.h拷贝到我们的项目中即可 接入cpp-httplib:header-only&#xff…

Kubernetes 1.27 版本基于(haproxy+keepalived)部署高可用集群

Kubernetes 1.27 版本基于(haproxykeepalived)部署高可用集群 二、系统架构2.1 架构基本需求2.2 架构图 三、环境准备3.1 云服务或虚拟机清单3.2 升级操作系统内核3.3 设置hostname3.4 修改hosts文件映射(注意替换你的规划每一台机器的IP&…

泛型深入~

1:泛型的概述的优势 2:泛型的好处 2:自定义泛型类 2:泛型类的原理 把出现泛型变量的地方全部替换成传输的真实数据类型 3:自定义泛型方法 4:自定义泛型接口 5:泛型通配符,上下限

03-1_Qt 5.9 C++开发指南_Qt核心特点(元对象系统特性:属性系统;信号与槽机制、动态类型转换;元对象特性测试实例)

Qt 是一个用标准 C编写的跨平台开发类库,它对标准 C进行了扩展,引入了元对象系统信号与槽、属性等特性,使应用程序的开发变得更高效。本章将介绍 Qt 的这些核心特点,对于理解和编写高效的 Ot C程序是大有帮助的;还介绍…

Servlet 项目创建和部署

目录 创建步骤: 1.创建项目 ​编辑2. 引入依赖 3.创建目录,复制内容 4.编写代码 5.打包 6.部署 7.验证 简化: 常见报错情况: 1.端口占用 2.路径错误 3.405 4.500 服务器代码抛出异常 5.依赖没下载好 创建步骤: 1.…

标注一致性计算

在统计学中,标注一致性(Inter-annotation agreement, IAA)用于评价独立观察者之间对同一现象进行评估时的一致程度。因此,本文讨论最多的是多位标注员对相同数据进行标注时的一致性评估方法。 一、Kappa统计量 评估一致性最简单…

Mysql高级篇(面试必看)

Mysql高级篇知识点,全篇手打,大家觉得有用的话点一个赞,持续更新 目录 1.Mysql锁的机制:粒度分类,思想分类,实现分类,状态分类,算法分类 2.Mysql的隔离级别:读未提交&…

视觉SLAM学习路线思维导图

整理了一下视觉SLAM学习路线的思维导图,防遗忘,不足的地方也希望各路大神能够不吝赐教。

Nginx(2)静态资源部署

静态资源 静态资源的配置指令静态资源优化配置静态资源压缩Gzip模块配置指令Gzip压缩功能的实例Gzip和sendfile共存问题gzip_static测试使用 静态资源的缓存处理浏览器缓存相关指令 Nginx的跨域问题解决静态资源防盗链防盗链的实现原理防盗链的具体实现 上网搜索访问资源是通过…

Java15——枚举类、注解、作业

1. 枚举类 跳了很多。。。 2. 注解 3. 作业 1. 注意:所有类共享静态属性 所以结果是 9,red 100,red package com.zsq.homework1;public class HM1 {public static void main(String[] args) {Cellphone cellphone new Cellphone();cel…

Java面试题大全(23年整理版)最新全面技巧讲解

程序员面试背八股,可以说是现在互联网开发岗招聘不可逆的形式了,其中最卷的当属 Java!(网上动不动就是成千上百道的面试题总结)你要是都能啃下来,平时技术不是太差的话,面试基本上问题就不会太大…

如何在 MATLAB 中进行图像分割(matlab仿真与图像处理系列第7期)

在 MATLAB 中进行图像分割有多种方法,下面介绍一些常用的方法: 基于阈值的二值化分割这是一种最简单的分割方法,将图像分为两个部分:背景和前景。其主要思想是,选择一个阈值,将图像中的像素值与阈值进行比较,将像素值大于阈值的像素标记为前景(白色),将像素值小于阈值…