Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A solution consists in subclassing <code>argparse.ArgumentParser</code> and redefining its <code>error()</code> method. In fact, upon error, <code>ArgumentParser</code> calls its <code>error()</code> method. The custom argument parsing can then be performed through the subclass instead of <code>argparse.ArgumentParser</code>. A model <code>error()</code> function is found in the source for <code>argparse</code>:</p> <pre><code>def error(self, message): """error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(sys.stderr) self.exit(2, '%s: error: %s\n' % (self.prog, message)) </code></pre> <p>It is for instance possible to raise an exception in <code>error()</code>, instead of printing a message, so that the code calling <code>parse_args()</code> takes charge of problems with the user parameters.</p> <p><strong>Original answer</strong>: according to the clarification in the comments, the following does not work. However, it provides a mechanism for accessing help messages from the sub-command functions:</p> <p>You almost have it: in each of your <code>*_command(args)</code> functions, you can test the size of <code>args</code> and print an error message if there are not enough arguments.</p> <p>If you want to use the automatically generated help, in your command functions, you can get it by passing the subparsers to each command, like so:</p> <pre><code>args.command(subparsers, args) # Instead of args.command(args) </code></pre> <p>Each <code>*_command()</code> function should then simply take two arguments instead of one. The automatically generated help is accessible through:</p> <pre><code>subparsers.choices['beaker'].print_help() # or print_usage() </code></pre> <p>for instance.</p> <p>You could alternatively choose to directly pass the particular subparser to each sub-command routine <code>*_command()</code>:</p> <pre><code>args.command(subparsers.choices[sys.argv[1]], args) </code></pre> <p>and then, in each <code>*_command(subparser, args)</code>, print the help with <code>subparser.print_help()</code>.</p>
 

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