通八洲科技

python getopt模块怎么用?

日期:2025-12-01 00:00 / 作者:舞夢輝影
Python的getopt模块用于规范解析命令行参数,支持短选项(如-h)和长选项(如--help)。通过getopt.getopt(args, shortopts, longopts)解析,返回(options, remainder),其中options为(option, value)列表,remainder为未解析参数。例如处理-i/--input、-o/--output和-h/--help:使用sys.argv[1:]获取参数,try-except捕获GetoptError异常;遍历opts设置对应变量,输出结果。短选项加:或长选项加=表示需参数,无则为开关型。适用于简单场景,复杂需求建议用argparse。

Python 的 getopt 模块用于解析命令行参数,适合处理短选项(如 -h、-v)和长选项(如 --help、--version)。它比直接使用 sys.argv 更规范,适用于简单的命令行工具。

基本语法

getopt.getopt(args, shortopts, longopts=[])

返回值是一个元组 (options, remainder),其中 options 是 (option, value) 的列表,remainder 是未被解析的参数。

常见用法示例

假设你想实现一个脚本,支持 -i 或 --input 指定输入文件,-o 或 --output 指定输出文件,-h 或 --help 显示帮助:

import sys
import getopt

def main():

默认值

input_file = None  
output_file = None  

# 获取命令行参数  
args = sys.argv[1:]  
try:  
    opts, remainder = getopt.getopt(args, 'hi:o:', ['help', 'input=', 'output='])  
except getopt.GetoptError as err:  
    print(err)  
    sys.exit(2)  

# 处理选项  
for opt, arg in opts:  
    if opt in ('-h', '--help'):  
        print("usage: script.py -i input -o output")  
        sys.exit()  
    elif opt in ('-i', '--input'):  
        input_file = arg  
    elif opt in ('-o', '--output'):  
        output_file = arg  

print(f"Input file: {input_file}")  
print(f"Output file: {output_file}")  
print(f"Other arguments: {remainder}")  

if name == 'main':
main()

选项说明规则

错误处理

如果用户输入了不支持的选项或缺少参数,getopt.GetoptError 会被抛出。建议用 try-except 包裹 getopt.getopt 调用,并给出提示。

基本上就这些。getopt 适合简单场景,如果功能复杂,推荐用 argparse 模块。但了解 getopt 有助于理解命令行解析的基本逻辑。