简体   繁体   English

Python SimpleXMLRPCServer返回值

[英]Python SimpleXMLRPCServer return value

I just started using a XMLRPC server and clients to connect my raspberry pi to a computer. 我刚开始使用XMLRPC服务器和客户端将树莓派连接到计算机。

My server looks like this: 我的服务器如下所示:

from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import numpy as np

allow_reuse_address = True   
ip = '...'
port = 8000  

class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)  

server = SimpleXMLRPCServer((ip, port), requestHandler=RequestHandler)
server.register_introspection_functions() 

def Spectrum():
    data = ... # it's a numpy array
    return data

server.register_function(Spectrum, 'Spectrum')  
server.serve_forever()

My client looks like this: 我的客户看起来像这样:

#!/usr/bin/env python

import xmlrpclib
import numpy as np

[...]

def getSpectrum():
try:
    s = xmlrpclib.ServerProxy(server)
    v = s.Spectrum()
    print v         

except:
    print "no data"

My server is running and my test function shows that it works. 我的服务器正在运行,我的测试功能表明它可以工作。 But my function getSpectrum() always throws an exception. 但是我的函数getSpectrum()总是抛出异常。 I figured out that it works fine if my return value is a float instead of a numpy array: 我发现,如果我的返回值是浮点数而不是numpy数组,则它可以正常工作:

def Spectrum():
    data = ... # it's a numpy array
    return float(data[0][0])

I don't have any idea what's wrong but I think it should be possible to return a numpy array. 我不知道出了什么问题,但我认为应该可以返回一个numpy数组。 Do you know how to fix that? 你知道怎么解决吗?

The xmlrpclib only supports marshalling of standard python types. xmlrpclib仅支持标准python类型的编组。 numpy arrays are an extension type and therefor cannot be serialized out of the box. numpy数组是扩展类型,因此无法直接序列化。 A simple solution would be to return a list representation of the numpy array and when you receive the data you turn it into a numpy array again: 一个简单的解决方案是返回numpy数组的列表表示形式,当您收到数据时,将其再次转换为numpy数组:

def Spectrum():
    data = ... # it's a numpy array
    return data.tolist()
...
def getSpectrum():
    try:
        s = xmlrpclib.ServerProxy(server)
        v = numpy.asarray(s.Spectrum())
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM