Skip to content

Instantly share code, notes, and snippets.

@ansig
Last active January 30, 2016 06:56
Show Gist options
  • Save ansig/10ada9c734a965fbc6f5 to your computer and use it in GitHub Desktop.
Save ansig/10ada9c734a965fbc6f5 to your computer and use it in GitHub Desktop.
Make class functions callable via command line
import sys
class MyClass(object):
def func1(self, arg1):
print "Invoked: func1({0})".format(arg1)
def func2(self, arg1, arg2):
print "Invoked: func2({0}, {1})".format(arg1, arg2)
def main(args):
if len(args) < 1:
raise Exception("Needs at least 1 argument with function name")
myClass = MyClass()
try:
func = getattr(myClass, args[0])
except AttributeError:
raise Exception("No such function: {0}".format(args[0]))
func(*args[1:])
if __name__ == '__main__':
try:
main(sys.argv[1:])
except Exception as err:
print "Script failed:\n{0}".format(str(err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment