一、Python提供了getopt 模块来获取命令行参数
python3 test.py arg1 arg2 arg3
getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式(-)和长选项模式(--)。该模块提供了两个方法及一个异常处理来解析命令行参数。
- getopt.getopt 方法
- getopt.getopt 方法用于解析命令行参数列表
- 语法格式如下:
getopt.getopt(args, options[, long_options])
二、Python 中也可以所用 sys 的 sys.argv 来获取命令行参数
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import sys
print('参数个数为:', len(sys.argv), '个参数。')
print('参数列表:', str(sys.argv))
执行以上代码,输出结果为:
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
其中:
- sys.argv 是命令行参数列表。
- len(sys.argv) 是命令行参数个数。
- sys.argv[0] 表示脚本名。