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

如何用argparse获取带空格和连字符的完整引号内参数?

解决argparse无法获取带连字符的完整引号参数问题

问题原因

当前代码使用nargs='+'时,argparse会将-c后的参数按空格拆分;当参数中出现-P这类以-开头的内容时,argparse会误将其识别为新的命令行选项,导致仅收集到该内容之前的部分。

解决方法

去掉nargs='+',让-c参数默认接受单个值。此时shell会将引号包裹的完整字符串作为单个参数传递给argparse,既不会拆分内容,也不会误判内部的-开头内容为选项。

修改后的代码:

from argparse import ArgumentParser

parser = ArgumentParser(usage='test.py help', prog='test')

parser.add_argument('-c', '--cmd', type=str, action='store', dest='build_cmd',
                    help='Mandatory.')
parser.add_argument('-l', '--build-mode', action='store_true', default=False,
                    help='Optional.')

options = parser.parse_args()

if options.build_cmd:
    print(options.build_cmd)

测试验证

执行python test.py -c 'build -P test' -l,会完整输出build -P test,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:22:12