Pass in a value into Python Class through command line

Posted by chrissygormley on Stack Overflow See other posts from Stack Overflow or by chrissygormley
Published on 2010-05-04T13:27:31Z Indexed on 2010/05/04 13:28 UTC
Read the original article Hit count: 232

Hello, I have got some code to pass in a variable into a script from the command line. The script is:

import sys, os

def function(var):
    print var

class function_call(object):
    def __init__(self, sysArgs):
        try:
            self.function = None
            self.args = []
            self.modulePath = sysArgs[0]
            self.moduleDir, tail = os.path.split(self.modulePath)
            self.moduleName, ext = os.path.splitext(tail)
            __import__(self.moduleName)
            self.module = sys.modules[self.moduleName]
            if len(sysArgs) > 1:
                self.functionName = sysArgs[1]
                self.function = self.module.__dict__[self.functionName]
                self.args = sysArgs[2:]
        except Exception, e:
            sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e))

    def execute(self):
        try:
            if self.function:
                self.function(*self.args)
        except Exception, e:
            sys.stderr.write("%s %s\n" % ("PythonCall#execute", e))

if __name__=="__main__":
    test  = test()
    function_call(sys.argv).execute()

This works by entering ./function <function> <arg1 arg2 ....>. The problem is that I want to to select the function I want that is in a class rather than just a function by itself. The code I have tried is the same except that function(var): is in a class. I was hoping for some ideas on how to modify my function_call class to accept this.

Thanks for any help.

© Stack Overflow or respective owner

Related posts about python

Related posts about classes