title: Custom tab completion in python argparse
body: <p>How to get shell tab completion cooperating with <code>argparse</code> in a Python script?  </p>
  
  <pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python
  import argparse
  
  def main(**args):
      pass
  
  if __name__ == '__main__':
      parser = argparse.ArgumentParser()
      parser.add_argument('positional', choices=['spam', 'eggs'])
      parser.add_argument('--optional', choices=['foo1', 'foo2', 'bar'])
      args = parser.parse_args()
      main(**vars(args))
  </code></pre>
  
  <p>With an executable flag set on the .py file, the expected results should be something like:</p>
  
  <pre class="lang-bash prettyprint-override"><code>$ ./example.py sp&lt;tab&gt;             
     -&gt;  completes to "./example.py spam"
  $ ./example.py --op&lt;tab&gt; 
     -&gt;  completes to "./example.py --optional"
  $ ./example.py --optional b&lt;tab&gt;
     -&gt;  completes to "./example.py --optional bar"
  $ ./example.py --optional f&lt;tab&gt;   
     -&gt;  completes to "./example.py --optional foo"
         and, additionally, prints  "foo1  foo2"  choices on stdout on a new line
  </code></pre>