我是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()
提前谢谢
答案 0 :(得分:0)
要执行阻止IO的await
函数,您可以通过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)
答案 1 :(得分:0)
我尝试了不同的变化:
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没有“运行”方法...我的错误在哪里?