Python argparse with — as the value

Question:

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 --
Asked By: Nick Falco

||

Answers:

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))
Answered By: wim

I had the same problem and found this hacky one-liner which modifies sys.argv:

import sys, argparse

sys.argv = [ ('__' if arg == '--' else arg) for arg in sys.argv ]

parser = argparse.ArgumentParser(description='A simple test')
parser.add_argument('path', help='Path of file (use `--` to read from stdin)')
args = parser.parse_args()

print('input is', 'stdin' if args.path == '__' else args.path)

Output:

> python test.py --
input is stdin
> python test.py foo.bar
input is foo.bar
Answered By: roipoussiere

Tested in Python 3.8:

Using the equal sign and quotes around the values definitely solves that issue:

--myarg="--"
Answered By: René
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.