Skip to content

Instantly share code, notes, and snippets.

@seler
Last active June 10, 2021 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seler/ec2e06417969bcbf7fab79c393135ecb to your computer and use it in GitHub Desktop.
Save seler/ec2e06417969bcbf7fab79c393135ecb to your computer and use it in GitHub Desktop.
import time
from handlers import handlers, invalid_command, Exit
def get_greeting():
commands = ", ".join(handlers)
return (
f"available commands are: {commands}\n"
"hit CTRL+C or type exit to exit"
)
def receive_command():
command, *arguments = input("$ ").split()
return command, arguments
def process_command(command, arguments, context):
command_function = handlers.get(command, invalid_command)
return command_function(*arguments, **context)
def send(response):
print(response)
def run_server():
context = {
"start_time": time.time(),
"info": "this is some fake data just to pass as example kwarg",
}
send(get_greeting())
while True:
command, arguments = receive_command()
response = process_command(command, arguments, context)
send(response)
if __name__ == "__main__":
try:
run_server()
except (Exit, KeyboardInterrupt):
print("exit")
import time
handlers = {}
class Exit(Exception):
pass
def register(name):
def decorate(f):
handlers[name] = f
return f
return decorate
@register("serverinfo")
def server_info(*args, info, **kwargs):
return f"this is server info: {info}"
@register("uptime")
def uptime(*args, start_time, **kwargs):
duration = time.time() - start_time
return f"this is uptime: {duration}"
@register("newaccount")
def create_new_account(username, password, **kwargs):
return f"new account registered: {username}"
@register("exit")
def exit(*_, **__):
raise Exit()
def invalid_command(*args, **kwargs):
return "invalid command"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment