[Python小笔记]命令行参数:sys.argv和getopt模块

一、sys.argv

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

#test_sys_argv.py
import sys
print(sys.argv)#命令行参数列表
print(sys.argv[0])
print(len(sys.argv))#命令行参数列表个数

在这里插入图片描述

二、getopt模块

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

该模块提供了两个方法及一个异常处理来解析命令行参数。

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 mix

#test_getopt.py
import sys,getopt
try:
	options,args = getopt.getopt(sys.argv[1:],"hf:v:a:",["help","fruit=","vehicle=","annimal="])
except getopt.GetoptError:
	sys.exit()#退出主程序
print(options,args)
  • 适用于短格式的输入:'hf:v:a:'
    h后面不带冒号表示可以不带参数,输入参数的格式为:
    -h -f arg1 -v arg2 -a arg3
    在这里插入图片描述

  • 适用于短格式的输入:['help','fruit=','vehicle=','annimal=']
    help后面不带等号表示可以不带参数,输入参数的格式为:
    –help --fruit arg1 --vehicle arg2 --annimal arg3
    在这里插入图片描述

  • 也可以长短模式混用
    在这里插入图片描述

  • 也可以选项输入多次
    在这里插入图片描述

  • opts接收可以解析的参数,当有剩余参数时,就被另一个变量args接收
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40844116/article/details/85695161