0

I want to use argparse to only show help and usage and nothing else.

My current code looks like:

import argparse
parser = argparse.ArgumentParser(prog='remove-duplicate-lines-except-blank-lines',
                                 usage='%(prog)s [options] [files...]',
                                 description='Remove duplicate line except white space')
args = parser.parse_args()

To get help I can run:

$ python origname.py -h

and

$ python origname.py --help

So far, so good. However, when I try to use file names without options, for example:

$ python origname.py inputfile.txt optputfile.txt

If gives me usage and an error.

usage: origname [options] [files...]
origname: error: unrecognized arguments: inputfile.txt optputfile.txt

How can I pass arguments without options when using argparse?

Just to be clear, I am handling the rest of the argument (ex. inputfile.txt optputfile.txt) etc. manually using sys.argv so I do not need argparse for that.

2
  • why are you handling it using sys.argv instead of with argparse? that seems counterintuitive Commented Sep 24, 2021 at 12:27
  • @gold_cy this is a legacy code scenario. I want to use argparse to create --help, do not want to touch rest of the code. Commented Sep 24, 2021 at 12:29

1 Answer 1

1

Instead of using parser.parse_args() use parser.parse_known_args().

import argparse
parser = argparse.ArgumentParser(prog='remove-duplicate-lines-except-blank-lines',
                                 usage='%(prog)s [options] [files...]',
                                 description='Remove duplicate line except white space')
parser.parse_known_args()

==>python foo.py --help
usage: remove-duplicate-lines-except-blank-lines [options] [files...]

Remove duplicate line except white space

optional arguments:
  -h, --help  show this help message and exit


==>python foo.py foo.txt
# nothing happens here
Sign up to request clarification or add additional context in comments.

Comments

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.