Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As of Python 3.3, <code>parse_args</code> checks its set of <code>seen_actions</code> against the set of actions that are required, and issues a <code>the following arguments are required...</code> error as needed. Previously it checked its list of remaining <code>positionals</code> and raised the <code>too few arguments</code> error message.</p> <p>So for newer versions, this snippet should do what you want:</p> <pre><code>parser = argparse.ArgumentParser() lat=parser.add_argument('lat', help="latitude") lon=parser.add_argument('lon', help="longitude") parser.add_argument('--method', help="calculation method (default: add)", default="add") class MyAction(argparse._StoreTrueAction): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, self.const) lat.required = False lon.required = False parser.add_argument('--list-methods', help="list available methods", action=MyAction) </code></pre> <p>Normally <code>lat</code> and <code>lon</code> are required positionals, but if the <code>--list...</code> action is taken, those actions are no longer required, and no error message is raised if they are missing.</p> <hr> <p>Another way to customize argparse is to use several parsers. In this case you could use one parser to check for the <code>--list-methods</code> option, and based on what it gets, call another that looks for the positionals.</p> <pre><code>parser1 = argparse.ArgumentParser(add_help=False) parser1.add_argument('--list-methods', help="list available methods", action='store_true') parser2 = argparse.ArgumentParser() parser2.add_argument('lat', help="latitude") parser2.add_argument('lon', help="longitude") parser2.add_argument('--method', help="calculation method (default: add)", default="add") parser2.add_argument('--list-methods', help="list available methods", action='store_true') def foo(argv): args,rest = parser1.parse_known_args(argv) if not args.list_methods: args = parser2.parse_args(argv) return args </code></pre> <p><code>parser2</code> responds to the help command. <code>parse_known_args</code> parses what it can, and returns the rest in a list. <code>parser2</code> could also have been write to take <code>rest, args</code> as arguments.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload