0

I'm not quite clear on how to use argparse and argcomplete. I'm trying to write a completion script that uses Bash to call a Python script, which uses argparse/argcomplete.

The Bash script:

#!/usr/bin/bash

_comp_func() {
    local cmds=${COMP_WORDS[@]}
    COMPREPLY=()
    COMPREPLY=`python argcomp.py $cmds`
}

The Python script argcomp.py:

!/usr/bin/env python3

import sys
from os import environ as ENV
sys.path += ["...path to argcomplete module"]

import argcomplete, argparse

def TestCompleter(**kwargs):
    return "foo bar baz"

def main():        
    parser = argparse.ArgumentParser(prog='argc')
    parser.add_argument('--foo', action='store_true')
    
    args = parser.parse_args()
    
    completer = TestCompleter
    completer(parser=parser)

    argcomplete.autocomplete(parser)

if __name__ == "__main__":
    main()

The idea being that when I type argc and hit , I can generate a list of completions using argcomplete.

If I type argc <TAB>, then it returns:

usage: argc [-h] [--foo]
argc: error: unrecognized arguments: argc

If I type argc --foo<TAB>, then it returns the same thing.

If I type argc foo, or anything else, it will return:

usage: argc [-h] [--foo]
argc: error: unrecognized arguments: argc foo

So it doesn't recognise the name of the program as an argument itself. I thought that was handled by argparse.ArgumentParser() itself, but when that didn't work I tried adding argc as the program for the ArgumentParser() method. That didn't work either.

I even tried changing the command from argc to baz, just in case it was a reserved word issue. As far as I can tell it isn't. Can anyone guide me on what I'm doing wrong here, and how to get this simple example working?

Lou
  • 2,200
  • 2
  • 33
  • 66
  • The name of the script is the first element `sys.argv`. This `sys.argv[0]` is used by `argparse` as the `prog` parameter in the `usage` display. It is not an 'argument'. The parsing is done on `sys.argv[1:]`. – hpaulj Dec 16 '20 at 19:59
  • Ah okay. Even when I omitted that argument, it was still coming up with the same problem though. Any idea how to get it to recognise 'argc' or whatever I choose as the command name as an argument? – Lou Dec 17 '20 at 09:27

0 Answers0