title: How to handle CLI subcommands with argparse
body: <p>I need to implement a command line interface in which the program accepts subcommands.</p>
  
  <p>For example, if the program is called “foo”, the CLI would look like</p>
  
  <pre><code>foo cmd1 &lt;cmd1-options&gt;
  foo cmd2
  foo cmd3 &lt;cmd3-options&gt;
  </code></pre>
  
  <p><code>cmd1</code> and <code>cmd3</code> must be used with at least one of their options and the three <code>cmd*</code> arguments are always exclusive.</p>
  
  <p>I am trying to use subparsers in argparse, but with no success for the moment. The problem is with <code>cmd2</code>, that has no arguments:</p>
  
  <p>if I try to add the subparser entry with no arguments, the namespace returned by <code>parse_args</code> will not contain any information telling me that this option was selected (see the example below).
  if I try to add <code>cmd2</code> as an argument to the <code>parser</code> (not the subparser), then argparse will expect that the <code>cmd2</code> argument will be followed by any of the subparsers arguments.</p>
  
  <p>Is there a simple way to achieve this with <code>argparse</code>? The use case should be quite common…</p>
  
  <p>Here follows what I have attempted so far that is closer to what I need:</p>
  
  <pre><code>parser = argparse.ArgumentParser()
  subparsers = parser.add_subparsers(help='Functions')
  parser_1 = subparsers.add_parser('cmd1', help='...')
  parser_1.add_argument('cmd1_option1', type=str, help='...')
  
  parser_2 = subparsers.add_parser(cmd2, help='...')
  
  parser_3 = subparsers.add_parser('cmd3', help='...')
  parser_3.add_argument('cmd3_options', type=int, help='...')
  
  args = parser.parse_args()
  </code></pre>