getopt 是 Python 标准库中用于解析命令行参数的模块,类似于 C 语言中的 getopt() 函数。它支持 Unix 风格的短选项(如 -h)和 GNU 风格的长选项(如 --help),但功能不如 argparse 丰富,适合编写简单脚本时快速处理命令行参数。
◆ ◆ ◆
核心概念
1、getopt.getopt() 是该模块的核心函数,用于解析参数。
2、支持短选项(如 -f)和长选项(如 --file)。
3、被解析的参数通常来自 sys.argv[1:],即命令行中除脚本名外的参数。
4、返回值为两个列表:
第一个列表包含 (option, value) 元组。
第二个列表是解析后剩余的非选项参数。
◆ ◆ ◆
应用举例
例 1:解析短选项
import sys, getopt
argv = sys.argv[1:] # 获取命令行参数opts, args = getopt.getopt(argv, "hf:", ["file="]) # -h 无参,-f 需要参数
for opt, val in opts: if opt == "-h": print("用法: script.py -f <文件名>") elif opt in ("-f", "--file"): print(f"指定文件: {val}")
运行:
python script.py -f data.txt
例 2:同时支持短选项与长选项
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], "u:p:", ["user=", "password="])
for opt, val in opts: if opt in ("-u", "--user"): print(f"用户名: {val}") elif opt in ("-p", "--password"): print(f"密码: {val}")
运行:
python script.py -u mediaTEA -p 123456
例 3:处理未知选项异常
import sys, getopt
try: opts, args = getopt.getopt(sys.argv[1:], "x:", ["example="])except getopt.GetoptError as e: print("参数解析错误:", e) sys.exit(1)
例 4:组合参数与位置参数
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], "n:")
for opt, val in opts: if opt == "-n": print(f"姓名: {val}")
for item in args: print(f"剩余参数: {item}")
运行:
python script.py -n Alice extra1 extra2
例 5:构建简易命令行帮助菜单
import sys, getopt
def usage(): print("使用说明:") print(" -i <input_file> 输入文件") print(" -o <output_file> 输出文件") print(" -h 显示帮助")
try: opts, args = getopt.getopt(sys.argv[1:], "hi:o:")except getopt.GetoptError: usage() sys.exit(2)
for opt, val in opts: if opt == "-h": usage() sys.exit() elif opt == "-i": input_file = val elif opt == "-o": output_file = val
◆ ◆ ◆
常用函数速览
getopt(args, shortopts, longopts=[])
解析命令行参数。
参数:
args:通常为 sys.argv[1:]
shortopts:字符串形式的短选项,如 "ab:"(其中 b 表示需要一个值)
longopts:可选,长选项列表,如 ["alpha", "beta="](带 = 表示需要值)
返回:返回两个列表:已解析的选项元组列表、剩余参数列表
异常:若格式错误会抛出 getopt.GetoptError
getopt.GetoptError
参数格式错误时抛出的异常类。
常用属性:
.msg:错误信息字符串
.opt:出错的选项名
用途:用于 try...except 中捕获参数解析错误
◆ ◆ ◆
补充说明
1、getopt 是轻量级命令行解析模块,适合参数结构简单、选项较少的脚本。
2、参数名不能含 =,否则会被解析失败。
3、对于复杂命令行解析(如子命令、默认值、类型验证),建议使用 argparse。
4、getopt 在 Windows 和 Unix 环境中均可使用,但语法偏向 Unix 风格。
“点赞有美意,赞赏是鼓励”