【问题标题】:Python Asynchronously Calling Synchronous FunctionPython异步调用同步函数
【发布时间】:2023-06-01 12:46:01
【问题描述】:

我是 Python 异步编程的新手,互联网并没有帮助我解决我的问题 - 你们中有人有解决方案吗?

我有一个无限循环,其中读取了一些传感器数据。但是,传感器读数很慢,所以我想等待传感器信号。

我对它的期望是这样的(只是示意图):

    import bno055 #sensor library
    import asyncio
    
    aync def read_sensor():
           altitude=bno055.read()
           #..and some other unimportant lines which I hide here
           return altitude


    def main():

       while 1:
          await current_altitude= read_sensor() #??? how can I "await" the sensor signals?
          #....some other lines which I hide here, but they need to run syncronously
          print(current_altitude)

       
      

   main()      

提前谢谢你

【问题讨论】:

标签: python-3.x asynchronous async-await raspberry-pi3 sensors


【解决方案1】:

await函数做阻塞IO你可以通过run_in_executor运行它

def read_sensor():
    altitude=bno055.read()
    #..and some other unimportant lines which I hide here
    return altitude

loop = asyncio.get_running_loop()
altitude = await loop.run_in_executor(None, read_sensor)

【讨论】:

  • 是的,我更新了答案,read_sensor 现在不应该是async
  • 它返回“await loop.run_in_executor(None, read_sensor)”的语法错误
【解决方案2】:

我尝试了不同的变体:

    def read_sensor():
        altitude=bno055.read()
        #..and some other unimportant lines which I hide here
        return altitude

    async def main():
      while 1:
        loop = asyncio.get_running_loop()
        altitude = await loop.run_in_executor(None, read_sensor)
        ##.....##

    asyncio.run(main())

-> 这会引发 asyncio 没有“运行”方法的错误...我的错误在哪里?

【讨论】:

  • 什么python解释器版本?