njcuk9999 / apero-utils

APERO affiliated utilities and tools
MIT License
3 stars 3 forks source link

[APERO] autocomplete arguments #260

Open njcuk9999 opened 1 month ago

njcuk9999 commented 1 month ago

There is a module that can make arguments autocomplete

import argparse
import argcomplete
from argcomplete.completers import ChoicesCompleter

def main():
    parser = argparse.ArgumentParser(description="Example script with tab completion")

    # Define possible values for arguments
    foo_choices = ['apple', 'banana', 'cherry']
    bar_choices = ['x', 'y', 'z']

    # Add arguments with completers
    parser.add_argument('--foo', help='Foo argument').completer = ChoicesCompleter(foo_choices)
    parser.add_argument('--bar', help='Bar argument').completer = ChoicesCompleter(bar_choices)

    # Integrate argcomplete
    argcomplete.autocomplete(parser)

    args = parser.parse_args()
    print(f"Foo: {args.foo}, Bar: {args.bar}")

if __name__ == "__main__":
    main()

However you need to do some stuff outside python:

We have to install argcomplete + activate it on a machine (Question: How do we do this inside the pip setup stuff?)

pip install argcomplete
activate-global-python-argcomplete

This goes inside every code that has arguments

#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
njcuk9999 commented 1 month ago

And to add a dymanic argument choice:

import argparse
import argcomplete
import os

def directory_completer(prefix, parsed_args, **kwargs):
    # Return a list of directories in the current directory
    return [d for d in os.listdir('.') if os.path.isdir(d) and d.startswith(prefix)]

def main():
    parser = argparse.ArgumentParser(description="Example script with dynamic tab completion")

    # Add an argument that uses the directory completer
    parser.add_argument('--dir', help='Directory argument').completer = directory_completer

    # Integrate argcomplete
    argcomplete.autocomplete(parser)

    args = parser.parse_args()
    print(f"Directory: {args.dir}")