Search code examples
pythonargparse

How to use "--" as an argument in python argparser


I have the following python code set up, in which the program would return "something" whenever the user pass -- as an argument:

#script.py

import argparse

parser = argparse.ArgumentParser()

parser.add_argument(
    "--",
    help="Prints something",
    action="store_true",
    dest="print_something",
)

args = parser.parse_args()

if args.print_something:
    print("something")

The output is as follows:

$ python .\script.py --

usage: script.py [-h] [--]
playground.py: error: unrecognized arguments: --

Argparse is not able to recognise the -- argument.

I tried using escape sequences, like putting -\-\- under parser.add_argument(, yet the program is not behaving the way it should.

There is, of course, a workaround using sys.arg, which goes something like:

import sys

if "--" in sys.argv:
    print("something")

But the above approach is impractical for projects with alot of arguments -- especially for those containing both functional and positional argument.

Therefore, is there anyway to parse the -- argument using argparser?


Solution

  • Not sure if this is what you mean, but using this logic you can detect -- and process other using something like this:

    import argparse
    
    parser = argparse.ArgumentParser()
    
    # Define a positional argument to capture `--` and any arguments after it
    parser.add_argument(
        'args',
        nargs=argparse.REMAINDER,
        help="Arguments after --"
    )
    
    parsed_args = parser.parse_args()
    
    # Check if `--` is in the arguments
    if '--' in parsed_args.args:
        print("Found -- in arguments")
        # You can process the arguments after `--` here
        remaining_args = parsed_args.args[parsed_args.args.index('--') + 1:]
        # process other arguments here
        print("Arguments after --:", remaining_args)
    else:
        print("No -- found in arguments")
    

    So to answer your question: yes, but its quite niche.