Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7603541
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T23:40:56+00:00 2026-05-30T23:40:56+00:00

I have tested optcomplete working with the optparse module. Its example is a simple

  • 0

I have tested optcomplete working with the optparse module. Its example is a simple file so I could get that working. I also tested it using the argparse module as the prior one is deprecated. But I really do not understand how and by whom the python program gets called on tab presses. I suspect bash together with the shebang line and the argparse (or optparse) module are involved in some way. I have been trying to figure this out (now gonna read the source code).

I have a little more complex program structure, which includes a wrapper around the piece of code which handles the arguments. Its argparse.ArgumentParser() instantiation and calls to add_argument() – which are superclassed into another intermediate module to avoid duplicating code, and wrapper around that is being called – are inside a function.

I want to understand the way this tab completion works between bash and python (or for that matter any other interpretor like perl).

NOTE: I have a fair understanding of bash completion (which I learned just now), and I think I understand the bash(only) custom completion.

NOTE: I have read other similar SO questions, and none really answer this Q.

Edit: Here is the bash function.
I already understood how the python module gets to know about words typed in the command line, by reading os.environ values of variables

$COMP_WORDS
$COMP_CWORD
$COMP_LINE
$COMP_POINT
$COMPREPLY

These variables have values only on tab press.
My question is how does the python module gets triggered?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T23:40:57+00:00Added an answer on May 30, 2026 at 11:40 pm

    To understand what’s happening here, let’s check what that bash function actually does:

    COMPREPLY=( $( \
        COMP_LINE=$COMP_LINE  COMP_POINT=$COMP_POINT \
        COMP_WORDS="${COMP_WORDS[*]}"  COMP_CWORD=$COMP_CWORD \
        OPTPARSE_AUTO_COMPLETE=1 $1 ) )
    

    See the $1 at the end? That means that it actually calls the Python file we want to execute with special environment variables set! To trace what’s happening, let’s prepare a little script to intercept what optcomplete.autocomplete does:

    #!/usr/bin/env python2
    import os, sys
    import optparse, optcomplete
    from cStringIO import StringIO
    
    if __name__ == '__main__':    
        parser = optparse.OptionParser()
    
        parser.add_option('-s', '--simple', action='store_true',
                          help="Simple really simple option without argument.")
    
        parser.add_option('-o', '--output', action='store',
                          help="Option that requires an argument.")
    
        opt = parser.add_option('-p', '--script', action='store',
                                help="Option that takes python scripts args only.")
        opt.completer = optcomplete.RegexCompleter('.*\.py')
        
        # debug env variables
        sys.stderr.write("\ncalled with args: %s\n" % repr(sys.argv))
        for k, v in sorted(os.environ.iteritems()):
            sys.stderr.write("  %s: %s\n" % (k, v))
    
        # setup capturing the actions of `optcomplete.autocomplete`
        def fake_exit(i):
          sys.stderr.write("autocomplete tried to exit with status %d\n" % i)
        sys.stdout = StringIO()
        sys.exit = fake_exit
    
        # Support completion for the command-line of this script.
        optcomplete.autocomplete(parser, ['.*\.tar.*'])
    
        sys.stderr.write("autocomplete tried to write to STDOUT:\n")
        sys.stderr.write(sys.stdout.getvalue())
        sys.stderr.write("\n")
    
        opts, args = parser.parse_args()
    

    This gives us the following when we try to autocomplete it:

    $ ./test.py [tab]
    called with args: ['./test.py']
      ...
      COMP_CWORD: 1
      COMP_LINE: ./test.py 
      COMP_POINT: 10
      COMP_WORDS: ./test.py 
      ...
      OPTPARSE_AUTO_COMPLETE: 1
      ...
    autocomplete tried to exit with status 1
    autocomplete tried to write to STDOUT:
    -o -h -s -p --script --simple --help --output
    

    So optcomplete.autocomplete just reads the environment, prepares the matches, writes them to STDOUT and exits. The result -o -h -s -p --script --simple --help --output is then put into a bash array (COMPREPLY=( ... )) and returned to bash to present the choices to the user. No magic involved 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code that I have tested and works: using (new Impersonator(Administrator,
I am using the following code to play audio file. I have tested the
I have tested the below script on a demo page which is not using
I have a class with a method that works and I have tested it
I have made a model using Sketchup, and have tested rendering it using Blender
I have tested this and the reason I asked the question is that it
I have this tested function below that works fine for fading an element in
I have tested a bit of assembler on Linux using the AT&T syntax. One
Firstly, I would like to say that I have tested if my link to
I'm trying to write username validation using jquery, I'm using jmsajax plugin.I have tested

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.