Skip to content

Instantly share code, notes, and snippets.

@mduheaume
Created March 13, 2013 00:22
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 mduheaume/5148370 to your computer and use it in GitHub Desktop.
Save mduheaume/5148370 to your computer and use it in GitHub Desktop.
CLI Helper
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