miron / NeonCore

Terminal based Cyberpunk Tabletop RPG with Nostr as database and openAI API compatible commands
3 stars 1 forks source link

tab completition for arguments #46

Closed miron closed 1 year ago

miron commented 1 year ago

here's an example of a simple command line application that uses the cmd module, and demonstrates how to implement tab-completion for arguments:

import cmd

class MyApp(cmd.Cmd):
    def do_greet(self, name):
        """
        Greets a person with their name.
        """
        print(f"Hello, {name}!")

    def complete_greet(self, text, line, begidx, endidx):
        """
        Tab-completion function for the greet command.
        """
        return [name for name in ["John", "Jane", "Bob"] if name.startswith(text)]

if __name__ == "__main__":
    MyApp().cmdloop()

This example defines a simple command greet that takes a single argument, a name. The complete_greet function is used to provide tab-completion for the name argument. In this example, it returns a list of three names ("John", "Jane", "Bob") that match the text entered by the user so far.

To test the tab-completion, start the application and enter the greet command followed by a space. Then press the tab key. The names that match the text entered so far should be displayed as suggestions.

The cmd module provides a built-in way to handle command-line arguments using the argparse module. You can use the do_command() method and the arg_string variable to access the arguments passed to a command, and the completenames() method to provide tab-completion for arguments. Here's an example:

import cmd

class Example(cmd.Cmd):
    def do_greet(self, arg):
        '''greet <name> - Greet the person with the provided name.'''
        print(f"Hello, {arg}!")

    def complete_greet(self, text, line, begidx, endidx):
        '''Tab-completion for the "greet" command.'''
        names = ["John", "Mary", "Mike", "Sarah"]
        if text:
            return [name for name in names if name.startswith(text)]
        else:
            return names

Example().cmdloop()
miron commented 1 year ago

Already implemented in code