Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[APERO] autocomplete arguments #260

Open
njcuk9999 opened this issue Jul 25, 2024 · 1 comment
Open

[APERO] autocomplete arguments #260

njcuk9999 opened this issue Jul 25, 2024 · 1 comment
Assignees

Comments

@njcuk9999
Copy link
Owner

njcuk9999 commented Jul 25, 2024

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 njcuk9999 converted this from a draft issue Jul 25, 2024
@njcuk9999 njcuk9999 self-assigned this Jul 25, 2024
@njcuk9999
Copy link
Owner Author

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}")

@njcuk9999 njcuk9999 moved this from In Progress to Todo in APERO-LBL Core/Science Jul 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Todo
Development

No branches or pull requests

1 participant