Created
March 13, 2013 00:22
-
-
Save mduheaume/5148370 to your computer and use it in GitHub Desktop.
CLI Helper
This file contains hidden or 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
import sys | |
import __main__ | |
class CLIUtility(object): | |
''' | |
A little helper for writing CLI tools. | |
Example: myclitool.py: | |
>>> cli = CLIUtility() | |
>>> | |
>>> @cli.command('reverse') | |
>>> def print_reversed_string(foo): | |
>>> print foo[::-1] | |
>>> | |
>>> if __name__ == "__main__": | |
>>> cli.run() | |
>>> | |
$ python myclitool.py reverse abcde | |
edcba | |
''' | |
commands = {} | |
def run(self): | |
try: | |
command_func = self.commands[sys.argv[1]] | |
except: | |
print 'Available commands are:' | |
for command_name in self.commands.keys(): | |
print "\t%s" % command_name | |
exit(1) | |
command_args = sys.argv[2:] | |
try: | |
command_func(*command_args) | |
except TypeError: | |
if command_func.__doc__: | |
print command_func.__doc__ % __main__.__file__ | |
else: | |
print 'Invlaid arguments.' | |
exit(1) | |
def command(self, command_name, *args, **kwargs): | |
def register_command(function): | |
self.commands[command_name]=function | |
return function | |
return register_command | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment