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.
CodePudding user response:
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