Python argparse with - as value

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

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

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

You should use this argument in the following program:

python myprogram.py --myarg value123

Is there a way to run this program with - as a value instead of "value 123"?

i.e

python myprogram.py --myarg --
+4
source share
1 answer

I suspect it is argparseimpossible to do . You can pre-process sys.argv, albeit 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))
+4
source

Source: https://habr.com/ru/post/1661236/


All Articles