iterative / shtab

↔️ Automagic shell tab completion for Python CLI applications
https://docs.iterative.ai/shtab
Other
378 stars 34 forks source link

[Question] Selecting from a predefined list #167

Open BjornFJohansson opened 9 months ago

BjornFJohansson commented 9 months ago

Hi all, I am trying to use shtab for the first time. I would like to autocomplete a positional argument from a list. I made a choice function titleselector that selects from a list based on a prefix. This does not work for me, but I suspect that there is an error in how I try to use shtab. I suspect that this use case is a common one? I could not find any code examples for this.

Help appreciated!

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import shtab  # for completion magic

tptitles = """\
TP01_Calculating_checksums_using_seguid_calculator
TP02_Visualizing_linear_and_circular_DNA_with_ApE
TP03_In-silico_sub_cloning_using_ApE
""".splitlines()

def titleselector(prefix):
    return [title for title in tptitles if title.startswith(prefix)]

parser = argparse.ArgumentParser(description='Correct TPs')
shtab.add_argument_to(parser, ["-s", "--print-completion"])  # magic!

parser.add_argument('title',
                    choices=tptitles,
                    help='tp to correct.').complete = titleselector

parser.add_argument('--student',
                    dest='studentinfo',
                    action='store',
                    help='a string thad identifies the student.')

args = parser.parse_args()
casperdcl commented 9 months ago

not sure what the titleselector is for. You can just remove the .complete = titleselector bit and probably also add a prog to ArgumentParser.

BjornFJohansson commented 9 months ago

Hi, and thanks for the feedback. The tptitles is a list with three strings. I would like to autocomplete one of the options from this list.

casperdcl commented 8 months ago

argparse choices are fully supported.

#!/usr/bin/env python3
import argparse, shtab
tptitles = """
TP01_Calculating_checksums_using_seguid_calculator
TP02_Visualizing_linear_and_circular_DNA_with_ApE
TP03_In-silico_sub_cloning_using_ApE
""".strip().split()
parser = argparse.ArgumentParser(prog='tpcorrect', description='Correct TPs')
shtab.add_argument_to(parser, ["-s", "--print-completion"])  # magic!
parser.add_argument('title', choices=tptitles, help='tp to correct.')
if __name__ == '__main__':
    args = parser.parse_args()