Python 使其他脚本可以访问串行输出

Python Make serial output accessible to other scripts

我目前有一个从串行设备获取提要的脚本。

feed.py

from serial import Serial
ser = Serial('COM27', 9600, timeout=5)

def scrape():
    while True:
        raw = ser.readline()
        raw = raw.decode('utf-8')
        if raw == "":
            pass
        else:
            print(raw)
    #print (raw.decode('utf-8'))
scrape()

我现在想做的是从其他 python 脚本访问该提要。 我确实尝试使用 SimpleXMLRPCServer 但无法获得输出

feed.py

from serial import Serial
from xmlrpc.server import SimpleXMLRPCServer
ser = Serial('COM27', 9600, timeout=5)

def scrape():
    while True:
        raw = ser.readline()
        raw = raw.decode('utf-8')
        if raw == "":
            pass
        else:
            print(raw)
try:
    server = SimpleXMLRPCServer(("localhost", 8000), allow_none=True)
    server.register_function(scrape)
    server.serve_forever()

except Exception as e:
    print(e)

listener.py

import xmlrpc.client

feed = xmlrpc.client.ServerProxy('http://localhost:8000')

print(feed.scrape())

我没有从监听器脚本中得到任何输出

当一个函数被注册时,那么期望该函数returns一个信息,而不仅仅是打印它,所以这就是你的逻辑失败的原因。

在这种情况下,最好注册 Serial 对象:

feed.py

from serial import Serial
from xmlrpc.server import SimpleXMLRPCServer

ser = Serial("COM27", 9600, timeout=5)

try:
    server = SimpleXMLRPCServer(("localhost", 8000), allow_none=True)
    server.register_instance(ser)
    server.serve_forever()

except Exception as e:
    print(e)

listener.py

import xmlrpc.client

ser = xmlrpc.client.ServerProxy("http://localhost:8000")

while True:
    raw = ser.readline()
    if raw:
        print(raw)

scrape return 什么都没有,只是打印输出,这是您的直接问题,但是当您要流式传输数据时,您必须填充缓冲区并读取不断地从它开始,使 XML-RPC(或任何其他基于 RPC 的协议)不合适。

XML-RPC 会产生大量开销,因为它在 TCP 之上的多个层上运行,而这正是您进行数据流传输所需要的。这意味着在每次 scrape 调用时,您还将生成并发送 HTTP 和 XML 负载。

如果您熟悉异步编程,请从 asyncio. If not, I'd start with sockets; if you're planning on having more than a single consumer, look into select 开始。