以-为值的Python argparse [英] Python argparse with -- as the value
本文介绍了以-为值的Python argparse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以使用argparse将--
作为值传递给Python程序,而无需使用等号(=)?
Is there a way to pass --
as a value to a Python program using argparse without using the equals (=) sign?
我添加到argparser的命令行参数的定义如下:
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
是否可以使用-作为值而不是'value123'来运行该程序?
Is there a way to run this program with -- as the value instead of 'value123'?
即
python myprogram.py --myarg --
推荐答案
我怀疑不可能使argparse
本机执行此操作.不过,您可以将sys.argv
进行预处理,作为一种非侵入式解决方法.
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))
这篇关于以-为值的Python argparse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文