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 无短参数
此时
getopt
的shortopts
应传入""
,必传参数,即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
无值
此时
getopt
的shortopts
应传入"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
有值
此时
getopt
的shortopts
应传入"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
此时
getopt
的shortopts
应传入"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 长参数无值
此时
getopt
的shortopts
应传入["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 长参数有值
此时
getopt
的shortopts
应传入["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))