Python argparse 以 -- 作为值

Python argparse with -- as the value

有没有办法在不使用等号 (=) 的情况下使用 argparse 将 -- 作为值传递给 Python 程序?

我添加到 argparser 的命令行参数定义如下:

parser.add_argument('--myarg', help="my arg description")

您可以在如下程序中使用此参数:

python myprogram.py --myarg value123

有没有办法 运行 这个程序用 -- 作为值而不是 'value123'?

python myprogram.py --myarg --

我怀疑 argparse 无法在本机执行此操作。不过,您可以预处理 sys.argv,作为一种非侵入式解决方法。

import sys
from argparse import ArgumentParser
from uuid import uuid4

sentinel = uuid4().hex

def preprocess(argv):
    return [sentinel if arg == '--' else arg for arg in argv[1:]]

def postprocess(arg):
    return '--' if arg == sentinel else arg

parser = ArgumentParser()
parser.add_argument('--myarg', help="my arg description", type=postprocess)
args = parser.parse_args(preprocess(sys.argv))