using serial port in python3 asyncio

后端 未结 8 2032
长情又很酷
长情又很酷 2021-02-08 09:39

i\'m trying and, so far, failing to use python asyncio to access a serial port.

i\'d really appreciate any tips on using the new python async framework on a simple fd.

8条回答
  •  孤街浪徒
    2021-02-08 10:11

    Another option is to write all your serial stuff with blocking calls, then run it in a different thread with run_in_executor:

    import asyncio
    import concurrent
    
    from serial import Serial
    
    # Normal serial blocking reads
    # This could also do any processing required on the data
    def get_byte():
        return s.read(1)
    
    # Runs blocking function in executor, yielding the result
    @asyncio.coroutine
    def get_byte_async():
        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
            res = yield from loop.run_in_executor(executor, get_byte)
            return res
    
    def get_and_print():
        b = yield from get_byte_async()
        print (b)
    
    s = Serial("COM11", 19200, timeout=10)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(get_and_print())
    

提交回复
热议问题