0

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?

2
  • 4
    That's a weird thing to want. -- conventionally has a very specific meaning. In isolation, you don't seem to need an option at all; if the program doesn't do anything without the option, it's not optional. Commented Aug 26, 2024 at 11:24
  • 3
    "is there anyway to parse the -- argument using argparser?" I'm going to say "no", since argparse will consider the use of -- having a special meaning, namely "end of options". It's unconvential, probably unwise, and likely impossible, to override that behaviour. Commented Aug 26, 2024 at 11:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, using the nargs=argparse.REMAINDER approach is just great and intuitive. Just what I wanted. Thanks!
glad to be of help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.