I have code to pass a variable to a script from the command line. I can pass any value in functionto for an argument var. The problem is that when I put functionin the class, the variable is not read in function. script:
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__":
function_call(sys.argv).execute()
This works by typing ./function <function> <arg1 arg2 ....>. The problem is that I want to select the function that I want, which is in the class, and not just the function itself. The code I tried is the same, except that function(var):is in the class. I was hoping for some ideas on how to change the class function_callto accept this.
If I want to pass a value Hello, I ran the script as follows: python function_call.py function Hello. Then it prints the variable varas Hello.
, . script , , . python function.py function hello , . python function.py A function hello.
, . - , .
_________________________________________________________________________________
. , .
class A:
def __init__(self):
self.project = sys.argv[2]
def run(self, *sysArgs):
pass
def funct(self):
print self.project
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 = getattr(A(), sysArgs[1])(*sysArgs[2:])
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__":
function_call(sys.argv).execute()
inst_A = A()
inst_A.funct()
.