Python argparse with - 作为值

时间:2016-11-18 20:18:32

标签: python argparse

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

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

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

你可以在这样的程序中使用这个参数:

python myprogram.py --myarg value123

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

python myprogram.py --myarg --

1 个答案:

答案 0 :(得分:4)

我怀疑不可能让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))