Reputation: 13
I am currently trying to make a program that will run commands. I want to have it so there is a list of commands and the program will take my input command, check to see if its in the list, and then run the command if it does. and if not I want it to print out Invalid Command.
while 1 == 1:
command = input("Daisy: ")
commands = ['cmd', 'google']
if command == 'cmd' or 'google':
if command == 'cmd':
os.system("start")
elif command == 'google':
webbrowser.open_new('google.ca')
this is currently what i have. I already made the list but youll notice in my if statement i want it to check to see if it equals cmd or google. I am going to have a lot more commands then this so in the nature of making things look pretty, i wanted to know if there was a way i could have the command check the list, run the command if its in the list, and if its not, print invalid command.
Upvotes: 0
Views: 49
Reputation: 149
I did a similar program, a little console, to help me on the developments.
the solution is a if-elif-else statement because every command is different to the other. So:
while 1 == 1:
command = input("Daisy: ")
if command == 'cmd':
os.system("start")
elif command == 'google':
webbrowser.open_new('google.ca')
elif command == 'new command':
# put here a new command
else:
print('Invalid Command')
Array commands and the first if statement aren't necessary because now there is "else" that intercept all invalid commands.
if you want see my code there is a link: DevUtils at line 38 i manage commands.
Upvotes: 0
Reputation: 13
I think the most versatile way would be using a dictionary and the exec funktion
commands = dict()
commands['google'] = "webbrowser.open_new(\"google.ca\")"
commands['cmd'] = "os.system(\"start\")"
if key in commands:
exec(commands[key])
Can't test this right now but it should work
Upvotes: 0
Reputation: 1644
You can create a function per command, and store the name for command and function to be executed in a dictionary. Like this:
def open_google():
webbrowser.open('google.ca')
commands = {'open_google': open_google}
while True:
# Get input here
if command in commands:
commands[command]()
This way you only have to create new functions, and add them to the dictionary. The logic in the main loop remains the same.
Upvotes: 3