sys. argv
Python 中使用段参数可使用 sys.argv 获取。
import sys
# 获取所有参数,以列表形式返回
sys.argv
# 第一个为脚本名称
sys.argv[0]
# 参数列表
sys.argv[1:]
# 传递参数
scr.py 42 immwindgetopt
getopt 支持参数模式为短选项 - 和长选项 -- 模式。
- 语法:
getopt.getopt (args, options='', long_options=[]) - 参数说明
args: 要解析的参数列表(一般为 args 的值)options: 短选项,传递字符串[long_options]: 长选项,传递列表
- 返回值
opts: 由元组组成的列表,元组中的值由参数和对应值组成;args: 其他参数
短选项
import sys
from getopt import getopt
# 先获取参数
argv = sys.argv[1:]
opts, args = getopt(argv, ab)
for opt, arg in opts:
if opt == '-a': # 判断是否为指定选项
print(arg) # 打印指定值
elif opt == '-b':
print(arg)
# 调用方式
test -a 1 -b 2长选项
import sys
from getopt import getopt
# 先获取参数
argv = sys.argv[1:]
# 短选项的值可不传递
opts, args = getopt(argv, '', ['abc='], '[def=]')
for opt, arg in opts:
if opt == '-abc':
print(arg)
elif opt == '-def':
print(arg)
# 调用方式
test.py --abc 123 --def 456
# 选项会自动补全为全称,所以下面的方法也是一样
test.py --a 123 --de 456
长选项自动补全如果有多个首字母一样,值会被覆盖。