0

In the application I'm currently working on, i want to include a feature in which the administrator has access to a sort of command line.
This is not the actual command line, instead it looks for keywords inside a Textbox that I define, and runs their linked functions with the input parameters.
For instance:

get user data: erikthered

...would run the method self.user_data('erikthered'), but I'm unsure how to get to this step elegantly, without using messy things like eval or exec.
These features should ideally also work for multiple parameters.
I apologise if this question is considered subjective, but I haven't really programmed something like this before, and I value other people's insights.
Thanks

UPDATE One way to do this, using exec, is to use a dictionary, like so:

    links = {'get users':'self.get_users(parameters)', 'get user data':'self.get_user_data(parameters)'}

    terminal = self.terminal
    line = str(terminal.index(INSERT).split('.')[0])
    #get index of line

    line = terminal.get(line+'.0', line+'.end')
    splitline = line.split(':')

    command = splitline[0]
    parameters = splitline[1].split(',')
    exec(links[command])

This is the code I have to get the text that the user has typed, bound to a return press. But I would prefer not to use exec.

3
  • Can i see the full code? Commented Jan 18, 2017 at 9:43
  • Does this question have anything to do with Tkinter or the actual command-line, or is this purely about how to parse and evaluate some made up command language? Commented Jan 18, 2017 at 10:24
  • You're right, it probably has more to do with parsing the inputs, than tkinter or the actual command-line Commented Jan 18, 2017 at 10:27

1 Answer 1

1

If you don't want to use exec, you can do a dictionary of functions:

def get_user_data(*args):
    print(*args)
# dictionary of functions
functions = {'get user data': get_user_data}

line = "get user data: erikthered, turtle"

# parse line
command, params = line.split(":")
params = [p.strip() for p in params.split(",")]
functions[command](*params)
Sign up to request clarification or add additional context in comments.

2 Comments

out of interest, would params.replace(" ", "").split(","), instead of the list comp, also work?
In this case, there will be problems with arguments containing spaces, e.g. "green turtle" will become "greenturtle".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.