Different behavior with different lists in a complete_xxx function in a cmd shell

41 views Asked by At

I am using the cmd module to create a simple shell. For two commands, I have two different lists. For one, the completion works as expected, but the other it doesn't.

[Good list] IntList="eth0", "eth1", "eth2"
 [Bad List] IntList="heth-0-0","heth-0-1","heth-0-2","heth-0-3","heth-0-4"

My routine looks like:

def complete_interface(self, text, line, begidx, endidx):
    return[ f for f in IntList if f.startswith(text)] 

When I run the shell and hit twice after 'interface', I see

Delem(eth2): interface eth
eth0  eth1  eth2  
Delem(eth2): interface eth
eth0  eth1  eth2  
Delem(eth2): interface eth

But when I use the other list, I get

Delem(heth0-0): interface heth-0-heth-0-
No such interface: heth-0-heth-0-
Delem(heth0-0): 

See how it is appending the beginning string with the second list? Not sure how to debug this...

1

There are 1 answers

1
Erik Sherk On
#!/usr/bin/env python3                                                                                                                                                                                                   
import cmd
                                                                             
Good = ['eth0', 'eth1', 'eth2', 'eth3']
Bad = ['heth-0-0', 'heth-0-1', 'heth-0-2', 'heth-0-3' ]
Lists = ['Good', 'Bad']

List = Good
Int = 'eth0'
line='line'

class DelemCmd(cmd.Cmd):
    """Simple shell command processor for delem."""
    global Int, List, Lists
    prompt = "Test: "

    def do_interface(self, arg):
        global Int
        "Set the interface to use."
        Int = arg

    def complete_interface(self, text, line, begidx, endidx):
        "Complete interface names"
        return [ f for f in List if f.startswith(text)]

    def do_node(self, arg):
        "Change the List we are using."
        global List
        if arg == "Good":
            List = Good
        elif arg == "Bad":
            List = Bad
        else:
            print(f'Bad arg {arg}')
            exit()
        print(List)

    def complete_node(self, text, line, begidx, endidx):
        return [ f for f in Lists if f.startswith(text)]

    def do_EOF(self, line):
        "Ctrl-D to quit."
        return True

    def do_quit(self, line):
        "Bye-bye!"
        return True

    def emptyline(self):
        """Called when an empty line is entered in response to the prompt."""
        if self.lastcmd:
            self.lastcmd = ""
            return self.onecmd('\n')

DelemCmd().cmdloop()