![](/img/trans.png)
[英]Python asyncio gather returned value from 'call_soon_threadsafe'
[英]How to get the returned value from asyncio loop?
我正在嘗試測量 rtl sdr dongle 捕獲的信號的功率水平,然后比較幾個測量值以獲得最佳功率水平,但我不知道如何立即將功率水平返回到我的主要功能。
這是我的代碼:
import asyncio
from rtlsdr import RtlSdr
import numpy as np
import time
global power
async def streaming():
#SDR CONFIGURATION
sdr = RtlSdr()
sdr.rs = 2.4e6
sdr.fc = 801e6
async for samples in sdr.stream(512):
global power
samples = samples - np.mean(samples)
calibrate = 3.2
power = np.mean(np.abs(samples ** 2))
#print('Relative power:', calibrate * 10 * np.log10(power), 'dB')
await sdr.stop()
sdr.close()
#return power
# i traied this function to return the result from streaming() but it didn't work !!
async def get_result():
global power
while True:
yield power
async def main():
global power
nb_config = 100
fpower = -100
for i in range(nb_config):
# Get the current event loop.
loop = asyncio.get_running_loop()
#try to get the power value from the loop
task = streaming()
power = loop.run_until_complete(asyncio.gather(*task))
loop.close()
if power > fpower :
fpower = power
print(10*np.log10(fpower))
asyncio.run(main(), debug=True)
簡短的回答是,如果您希望異步函數產生多個值,只需產生它們:
async def powers(): # was 'streaming', but that doesn't seem to describe it
...
async for samples in sdr.stream(512):
samples = samples - np.mean(samples)
calibrate = 3.2
power = np.mean(np.abs(samples ** 2))
yield power
await sdr.stop()
sdr.close()
但是你需要在main
中獲取這些值:
async def main():
...
async for power in powers():
print(power)
由於這是協作多線程,任何時候 python 在main()
(或其他任何東西)中,它都不會在powers()
中。 這是否重要取決於相關工具的構建方式,但如果您的 SDR 仍在輸出數據,您可能需要注意不要在代碼變長時填滿緩沖區。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.