我正在为我编写的Python模块构建一个远程API。代码将通过UDP从Matlab检索原始字符串,解析它,并通过这些字符串调用API。实际上,我希望使用Python语法在Matlab端与我的API进行交互。
说我有一个功能:
commands = {'foo':foo}
def foo(arg1=default, arg2=default):
...
return bar
在Matlab中,我通过UDP发送:
'foo(arg1='in1', arg2='in2')'
在Python服务器端,我有一个字典,函数名称作为键,相应的函数本身作为值。我能够调用没有参数的简单函数,或者简单的args,但是对于更复杂的东西,我无法让它工作。
所以,我有函数,我把args作为一个字符串,我怎样才能以最直接的方式将args传递给函数?
即
command = commands['foo']
command(argString)
如果可能的话,我想避免使用kwargs。我研究了类似的问题,但还没有发现任何有效的问题。
修改 这是一些更具体的代码;服务器已在运行,UDP数据包在“中断”处理,其中Determ_command被调用。
发送的matlab数据包是:
cmd = ['get_surrounding_elevation(mode=''coords'',window=3,' ...
'coordinates=Coordinate(36.974117, -122.030796))'];
Python结束:
def func_explode(self, s):
pattern = r'(\w[\w\d_]*)\((.*)\)$'
match = re.match(pattern, s)
if match:
return list(match.groups())
else:
return []
def determine_command(self, command):
"""
Parse raw input and execute specified function with args
:param command: The raw command retrieved from UDP
:return: the command that was executed
"""
funcArray = self.func_explode(command)
cmd = self.commands[funcArray[0]]
args = funcArray[1]
print cmd(mode='coords', window=3, coordinates=Coordinate(36.974117, -122.030796)) #this works
try:
cmd(eval(args)) #this, and other permutations of, doesn't work
print cmd
except:
print "Command Not Found"
return cmd
答案 0 :(得分:-1)
试试这个:
def foo(*args):
for a in args:
print a
#main for test
# call as foo (a1, a2) etc
foo(1, 2, 3)
foo("abc", 1)
输出:
1
2
3
ABC
1