From 7e708ba4ab1f599a9b5b121d09356731d157ed22 Mon Sep 17 00:00:00 2001 From: Ian Adam Naval Date: Thu, 26 Feb 2015 17:47:06 -0500 Subject: [PATCH] Made registering commands better Registering commands requires adding the name as a string so that we can have nice PEP 8-compatible class names for commands. --- psh/__init__.py | 11 +++++++++++ psh/commands.py | 12 +++++++----- psh/example_cmd.py | 12 ++++++------ 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/psh/__init__.py b/psh/__init__.py index e69de29..6bd963c 100644 --- a/psh/__init__.py +++ b/psh/__init__.py @@ -0,0 +1,11 @@ +from psh.commands import registered_cmds + +# Import the exported commands +from psh.example_cmd import * + +# Instantiate the registered commands +for name, cls in registered_cmds.items(): + globals()[name] = cls() + +# Only export the names of registered commands +__all__ = registered_cmds.keys() diff --git a/psh/commands.py b/psh/commands.py index ab41676..164fd58 100644 --- a/psh/commands.py +++ b/psh/commands.py @@ -38,9 +38,11 @@ class BaseCommand(object): return cmd -registered_cmds = [] +registered_cmds = {} -def register_cmd(cls): - """Decorator for putting all of the commands in one nice place.""" - registered_cmds.append(cls.__name__) - return cls +def register_cmd(name): + def decorator(cls): + """Decorator for putting all of the commands in one nice place.""" + registered_cmds[name] = cls + return cls + return decorator diff --git a/psh/example_cmd.py b/psh/example_cmd.py index 8abf205..897dda7 100644 --- a/psh/example_cmd.py +++ b/psh/example_cmd.py @@ -1,8 +1,8 @@ from psh.commands import BaseCommand, register_cmd -@register_cmd -class example_cmd(BaseCommand): +@register_cmd("example") +class Example(BaseCommand): """Simple command that just returns 'example' and 'command'. Does nothing at all with the input.""" @@ -13,13 +13,13 @@ class example_cmd(BaseCommand): return output_generator -@register_cmd -class echo(BaseCommand): +@register_cmd("echo") +class Echo(BaseCommand): """Echoes anything from the command line arguments as well as input from the previous command.""" - def __init__(self, args): - super(echo, self).__init__() + def __init__(self, args=[]): + super(Echo, self).__init__() self.args = args def call(self,*args,**kwargs):