我正在尝试发送一个数字列表(特别是 numpy 或 python 的列表)并使用 xml-rpc 获取它们的总和,以熟悉环境。我总是在客户端收到错误。
<Fault 1: "<type 'exceptions.TypeError'>:unsupported operand type(s) for +: 'int' and 'list'">
服务器端代码:
from SimpleXMLRPCServer import SimpleXMLRPCServer
def calculateOutput(*w):
return sum(w);
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(calculateOutput,"calculateOutput");
server.serve_forever()
客户端代码:
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
print(proxy.calculateOutput([1,2,100]);
有人知道如何解决这个问题吗?
最佳答案
通过 proxy.calculateOutput([1,2,100])
作为 proxy.calculateOutput(1,2,100)
发送,或将服务器端函数的参数从 defcalculateOutput(*w):
到defcalculateOutput(w):
。
顺便说一句,您不需要分号。
可以用一个简短的示例来说明此行为的原因
>>> def a(*b):
>>> print b
>>> a(1,2,3)
(1, 2, 3)
>>> a([1,2,3])
([1, 2, 3],)
正如您从输出中看到的,使用神奇的 asterix 会将您传递给函数的许多参数打包为元组本身,以便它可以处理 n
个参数。当您使用该语法时,当您发送已包含在列表中的参数时,它们会被进一步打包到一个元组中。 sum()
仅期望列表/元组作为参数,因此当它尝试对包含的列表求和时会收到错误。
关于python XML-RPC 向服务器发送参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10915691/