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
.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.