【问题标题】:Python Make serial output accessible to other scriptsPython 使其他脚本可以访问串行输出
【发布时间】:2019-12-18 05:32:33
【问题描述】:

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

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())

监听器脚本没有输出

【问题讨论】:

    标签: python python-3.x xml-rpc pyserial


    【解决方案1】:

    scrape 不返回任何内容,而只是打印输出,这是您的直接问题,但是当您正在寻找流数据时,您必须填充一个缓冲区并连续读取它,从而使 XML-RPC (或任何其他基于 RPC 的协议)不合适。

    XML-RPC 在 TCP 之上的多个层上运行时会带来大量开销,而这正是数据流所需的全部。这意味着在每次 scrape 调用中,您还将生成和发送 HTTP 和 XML 有效负载。

    如果您熟悉异步编程,请从 asyncio 开始。如果没有,我会从sockets 开始;如果您计划拥有多个消费者,请查看select

    【讨论】:

      【解决方案2】:

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

      在这种情况下最好注册 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)
      

      【讨论】:

      • 完美.. 你展示的东西是有道理的。总是很简单
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2015-07-30
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 2018-01-22
      • 2020-01-12
      相关资源
      最近更新 更多