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屋!
查看全文