菜鸟教程《Python 3 教程》笔记 EX 01:命令行参数

笔记带有个人侧重点,不追求面面俱到。

1 命令行参数

出处: 菜鸟教程 - Python3 命令行参数

1.1 基础用法

Python 中可以所用 syssys.argv 来获取命令行参数:

注意: sys.argv[0] 为脚本名。

实例:

test.py 文件:

#!/usr/bin/python3

import sys

print ('参数个数为:', len(sys.argv), '个参数。')
print ('参数列表:', str(sys.argv))
print ('脚本名:', str(sys.argv[0]))

运行结果:

>> python test.py arg1 arg2 arg3
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
脚本名: test.py

1.2 getopt 模块

getopt 模块是专门处理命令行参数的模块,用于获取命令行选项和参数。该模块提供了两个方法及一个异常处理来解析命令行参数。

1.2.1 getopt.getopt 方法

语法:

getopt.getopt(args, shortopts, longopts=[])

参数:

  • args:要解析的命令行参数列表;
  • shortopts:接收字符串,解析为“短选项”。shortopts 后的冒号 : 表示该选项必须有附加的参数,不带冒号表示该选项不附加参数;
  • longopts:接收列表,解析为“长选项”。longopts 后的等号 = 表示如果设置该选项,必须有附加的参数,否则就不附加参数。

返回值:

  • opts:由元组 (opt, value) 组成的列表。例如输入"-h -i inputfile -o outputfile" 返回值就是 [(‘-h’, ‘’), (‘-i’, ‘inputfile’), (‘-o’, ‘outputfile’)];
  • args:参数(value)列表,包含除了长选项和短选项以及各自选项的参数以外的其他未知的参数。

注意:

  1. 长选项和短选项以及各自的参数都会按先后次序放在 opts 中;
  2. 返回的 opt 里面,--- 都被保留下来了;
  3. 长选项没有写完的时候,会被自动补全。比如用户输入的是 --u,通过 getopt 会被自动补全--user

实例:

# test.py

import sys
import getopt

def site():
    argv = sys.argv[1:]  # 以空格分割的字符串列表

    try:
        opts, args = getopt.getopt(argv, "abn:u:", ["name=", "url="])# 长选项模式
    except Exception as err:
        print(err)

    print("opts: ", opts)
    print("args: ", args)


if __name__ == "__main__":
    site()

输出:

1)正常使用

>>> python test.py -a -b -u item1 -n item2 --n item3 --url item4
opts:  [('-a', ''), ('-b', ''), ('-u', 'item1'), ('-n', 'item2'), ('--name', 'item3'), ('--url', 'item4')]
args:  []

2)只输入参数

>>> python test.py item1 item2
opts:  []
args:  ['item1', 'item2']

3)只输入选项

>>> python test.py -a
opts:  [('-a', '')]
args:  []

>>> python test.py -n
option -n requires argument  # 报错

4)错误输入选项

>>> python test.py -
opts:  []
args:  ['-']

>>> python test.py --
opts:  []
args:  []

>>> python test.py ---
option --- not recognized  # 报错

>>> python test.py -c
option -c not recognized  # 报错

>>> python test.py ---b
option ---b not recognized  # 报错

>>> python test.py -n-a
opts:  [('-n', '-a')]
args:  []

>>> python test.py -a-n
option -- not recognized  # 报错

>>> python test.py -a--n
option -- not recognized  # 报错

5)错误输入参数

>>> python test.py -a item
opts:  [('-a', '')]
args:  ['item']

>>> python test.py -aitem
option -i not recognized  # 报错

>>> python test.py -antem
opts:  [('-a', ''), ('-n', 'tem')]
args:  []

>>> python test.py -abntem
opts:  [('-a', ''), ('-b', ''), ('-n', 'tem')]
args:  []

>>> python test.py -acntem
option -c not recognized

>>> python test.py -n item1 -a item2 --n item3
opts:  [('-n', 'item1'), ('-a', '')]
args:  ['item2', '--n', 'item3']

>>> python test.py -n item1 item2 -a
opts:  [('-n', 'item1')]
args:  ['item2', '-a']

>>> python test.py item1 item2 -a
opts:  []
args:  ['item1', 'item2', '-a']

总结:欢迎指正、补充

  1. 命令行参数从左到右、依次解析
  2. 一般情况下以空格分割选项和参数,附加参数的短选项后紧跟的参数也可以被解析,例如:-nitem
  3. 解析时,先碰到未定义的选项时,会报错,先碰到多余的参数时,之后的参数都被放入返回值 args 中;
  4. 短选项可以采用 -abn 的样式输入,无附加参数的选项必须在前,否则会报错。

1.2.2 getopt.gnu_getopt 方法

语法:

getopt.gnu_getopt(args, shortopts, longopts=[])

此函数与 getopt() 类似,区别在于它默认使用 GNU 风格的扫描模式。这意味着选项和非选项参数可能会混在一起。getopt() 函数将在遇到非选项参数时立即停止处理选项。

如果选项字符串的第一个字符为 +,或者如果设置了环境变量 POSIXLY_CORRECT,则选项处理会在遇到非选项参数时立即停止。

1.2.3 Exception getopt.GetoptError

当参数列表中出现不可识别的选项或者当一个需要参数的选项未带参数时将引发此异常。此异常的参数是一个指明错误原因的字符串

对于长选项,将一个参数传给不需要参数的选项也将导致引发此异常。(没发现)

msg 和 opt 属性会给出错误消息和关联的选项;如果没有关联到异常的特定选项,则 opt 将为空字符串。

报错 1:

需要参数的选项未带参数。

报错 2:

如果 longopts 为 [‘foo’, ‘frob’],则选项 --fo 将匹配为 --foo,但 --f 将不能得到唯一匹配,因此将引发 GetoptError。

1.2.4 exception getopt.error

GetoptError 的别名,用于向后兼容。

扩展阅读: 《Python 官方文档》:getopt — C 风格的命令行选项解析器

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猎猫骑巨兽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值