为何argparse帮助输出中可选参数位于位置参数之前?
关于argparse生成usage信息中参数顺序的疑问
脚本代码
import argparse import sys from fontbro import Font def get_font_format(font_path, ignore_flavor): """ Gets the font format: otf, ttf, woff, woff2. :param font_path: Path to the font file. :param ignore_flavor: If True, the original format without compression will be returned. :returns: The format. :rtype: str or None """ font = Font(font_path) return font.get_format(ignore_flavor=ignore_flavor) def main(): parser = argparse.ArgumentParser(description='Get the font format of a font file.') parser.add_argument('font_path', type=str, help='The path to the font file') parser.add_argument('--ignore_flavor', action='store_true', help='Return original format without compression if set to True') # Print help if no arguments supplied if len(sys.argv)==1: parser.print_help(sys.stderr) sys.exit(1) args = parser.parse_args() # Get and print the font format format = get_font_format(args.font_path, args.ignore_flavor) print(format) if __name__ == "__main__": main()
实际输出的帮助信息
无参数运行脚本时,得到的usage部分如下:
usage: FontOpsGetFontFormat.py [-h] [--ignore_flavor] font_path Get the font format of a font file. positional arguments: font_path The path to the font file options: -h, --help show this help message and exit --ignore_flavor Return original format without compression if set to True
疑问
我原本期望的usage格式是:
usage: FontOpsGetFontFormat.py font_path [-h] [--ignore_flavor]
按常规理解位置参数应该排在前面,这个认知是否有误?
解答
你的理解完全正确,从通用命令行工具的使用习惯来看,位置参数确实应该放在可选参数之前。但argparse模块默认的usage生成逻辑是先列出所有可选参数(包括-h/--help),再列出位置参数,这是它内置的格式规则,并非你的认知错误。
如果想要得到你期望的usage格式,可以通过自定义usage参数覆盖argparse的默认生成结果,修改ArgumentParser的初始化代码即可:
parser = argparse.ArgumentParser( description='Get the font format of a font file.', usage='%(prog)s font_path [-h] [--ignore_flavor]' )
其中%(prog)s是argparse的占位符,会自动替换为当前脚本的文件名。修改后再运行脚本,无参数时输出的usage就会符合你的预期。
内容的提问来源于stack exchange,提问作者fmotion1
相关产品推荐
相关产品推荐

