You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ArgumentParser是否支持ffmpeg式的单文件对应独立参数?

如何用argparse解析“选项-文件”成对的命令行参数?

我希望应用能处理多个文件,每个输入文件对应一组独立选项,类似ffmpeg的命令行参数模式,示例命令如下:

python my.py -a file_a -b file_b --do-stuff=x file_c

我尝试了以下argparse代码:

parser = argparse.ArgumentParser()
parser.add_argument("-a", action="store_true")
parser.add_argument("-b", action="store_true")
parser.add_argument("--do-stuff", type=str)
parser.add_argument("files", type=pathlib.Path, nargs="+")
args = parser.parse_args()

但运行时出现错误:

error: unrecognized arguments: file_b file_c

我的目标是解析后得到如下映射关系:

file_a: {a: True}
file_b: {b: True}
file_c: {do_stuff: 'x'}

argparse本身不支持这种“选项与后续文件一一绑定”的语法,因为它默认将所有选项视为全局参数,而非专属某个文件。要实现ffmpeg这种风格的解析,最直接的方式是手动遍历命令行参数:

手动解析实现代码

import sys
import pathlib

def parse_args():
    file_options = {}
    current_options = {}
    i = 1  # 跳过脚本名
    while i < len(sys.argv):
        arg = sys.argv[i]
        if arg.startswith('-'):
            # 处理短选项和长选项
            if arg == '-a':
                current_options['a'] = True
                i += 1
            elif arg == '-b':
                current_options['b'] = True
                i += 1
            elif arg.startswith('--do-stuff='):
                _, value = arg.split('=', 1)
                current_options['do_stuff'] = value
                i += 1
            else:
                raise ValueError(f"未知选项: {arg}")
        else:
            # 绑定当前选项到文件,然后重置选项集合
            file_path = pathlib.Path(arg)
            file_options[file_path] = current_options.copy()
            current_options.clear()
            i += 1
    return file_options

if __name__ == '__main__':
    result = parse_args()
    for file, opts in result.items():
        print(f"{file}: {opts}")

运行示例命令后,输出与预期一致:

file_a: {'a': True}
file_b: {'b': True}
file_c: {'do_stuff': 'x'}

如果非要基于argparse实现,只能通过定义子命令或自定义action的方式,但会让命令格式变得复杂,远不如手动解析直接灵活。


内容的提问来源于stack exchange,提问作者anatolyg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 16:57:21