命令行介绍
在某些特定的时候,为了使python程序能够更方便的接受用户传入的实参,命令行参数就此出现。
它能够将用户在shell console等输入的实参带进Python程序,为Python程序的可交互性提升了更好的体验。
而今天主要介绍的,便是是使用getopt模块来解析命令行参数
实现Python程序的可交互性
正文
getopt 官方文档
官方文档:https://docs.python.org/3.1/library/getopt.html
getopt 模块
This module helps scripts to parse the command line arguments in sys.argv. It supports the same conventions as the Unix getopt() function (including the special meanings of arguments of the form ‘-‘ and ‘–‘). Long options similar to those supported by GNU software may be used as well via an optional third argument.
根据官方文档介绍,getopt
模块可以帮助Python脚本来解析命令行参数,且getopt
模块也支持长(--)
、短(-)
参数。
该模块主要有两个函数
getopt.getopt
getopt.gnu_getopt
以及一个报错处理
getopt.GetoptError
下面我们主要讲解 getopt.getopt
及其相关参数
getopt.getopt 函数说明
getopt.getopt(args, options[, long_options])
方法参数说明:
args: 要解析的命令行参数列表。此列表一般通过 sys.argv 获取
options : 以字符串的格式定义,options 后的冒号 : 表示如果设置该选项,必须有附加的参数,否则就不附加参数。
long_options : 以列表的格式定义,long_options 后的等号 = 表示该选项必须有附加的参数,不带冒号表示该选项不附加参数。
该方法返回值由两个元素组成: 第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有 - 或 -- 的参数。
参数详解
- args 一般我们需要解析在命令行输入的所有参数,使用sys.argv[1:]获取
我创建见了一个名为 aaa.py 的python程序,并输入以下内容
import sys
args = sys.argv
for