Python argparse with — as the value

烂漫一生 提交于 2019-12-10 17:25:58

问题


Is there a way to pass -- as a value to a Python program using argparse without using the equals (=) sign?

The command line arguments that I added to the argparser are defined like below:

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

You would use this argument in a program like this:

python myprogram.py --myarg value123

Is there a way to run this program with -- as the value instead of 'value123'?

i.e

python myprogram.py --myarg --

回答1:


I suspect it will not be possible to make argparse do this natively. You could pre-process sys.argv though, as a non-intrusive workaround.

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))


来源:https://stackoverflow.com/questions/40685320/python-argparse-with-as-the-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!