Last active
October 31, 2022 04:17
-
-
Save andrew-stclair/ce836ad339f8c51da50f7c9313bb7dd7 to your computer and use it in GitHub Desktop.
Python Prompt - An example of a prompt like program in python, this does not use the match function from Python 3.10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Variables | |
storage = { | |
'prompt': "❯", | |
'username': "root", | |
'hostname': "ubuntu" | |
} | |
# Default 'command not found' command | |
def h_noop(_): | |
"""An error occured, no op called""" | |
print("Error: Command not found") | |
# Top level commands | |
def h_help(_): | |
"""Gets a list of commands""" | |
for function in functions: | |
print(f"{function} - {functions.get(str(function), h_noop).__doc__}") | |
def h_exit(_): | |
"""Quit the program""" | |
quit() | |
def h_config(args): | |
"""Get/Set a configuration item""" | |
global storage | |
args = args.split() | |
if args[0] == "print": | |
for item in storage: | |
print(f"{item} - {storage.get(str(item), 'Error')}") | |
else: | |
if len(args) <= 1: | |
if args[0] in storage: | |
print(f"Current {args[0]}: '{storage[args[0]]}'") | |
else: | |
print(f"Error: {args[0]} does not exist") | |
else: | |
storage[args[0]] = args[1] | |
# Command directory | |
functions = { | |
"help": h_help, | |
"config": h_config, | |
"exit": h_exit | |
} | |
# Prompt | |
while(True): | |
command = input(f"{storage['username']}@{storage['hostname']}{storage['prompt']} ") | |
command = command.split() | |
functions.get(command[0], h_noop)(" ".join(command[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment