7

When using Python's argparse module you can use parse_known_args() to parse only arguments that are known to the parser and any additional arguments are returned separately.

However, this fact is not denoted in the usage/help string. Of course I could put it in the description field of the parser, but I wonder if there's a nice way to include it in the usage line.

What I'm looking for is an output of e.g. usage: test [-h] ... instead of usage: test [-h]

2 Answers 2

4

I think you could do this with a combination of format_usage() and the ArgumentParser attribute usage. Note that that section shows usage as a keyword argument to the constructor, however, inspecting the source for usage shows that you can access it after construction as parser.usage.

I imagine your final solution would look something like:

parser = argparse.ArgumentParser()
# Add arguments...
usage = parser.format_usage()
parser.usage = usage.rstrip() + ' ...\n'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that almost did the job. The usage string ends with a \n so that needs to be taken care of first: parser.usage = '%s ...\n' % parser.format_usage().rstrip()
3

parse_known_args() is for the convenience of the programmer writing the program, not something that the user of the program needs to worry about. If you properly define your command-line arguments, argparse gives you something similar automatically:

>>> import argparse
>>> p = argparse.ArgumentParser(prog='command')
>>> x=p.add_argument("foo", nargs=argparse.REMAINDER)
>>> p.parse_args(["--help"])
usage: command [-h] ...

positional arguments:
  foo

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

2 Comments

Ah nice, unfortunately the foo [foo ...] style it rather uncomfortable for my case since it's actually a single argument that may contain spaces in an environment where there are no quotes or backslashes, i.e. the only arg that can contain spaces is the last one by merging it with any non-args.
Ah, try nargs=argparse.REMAINDER. That will put any remaining positional arguments in a list, and conveniently puts "..." in the help string as you want.

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.