Using `async for` inside a timeout function in Python

37 Views Asked by At

I am trying to print output from an information stream and cancel the stream after 5 seconds. My issue is that the documentation suggests using async for to print the data stream, but I am unable to cancel the stream and exit the main function after the specified time. I can get the rest of the code to run, but after 5 seconds the function keeps on running. Here is a minimum reproducible example based on a similar question:

import asyncio
import datetime
from rtlsdr import RtlSdr

sdr = RtlSdr()

async def main():
    starttime = datetime.datetime.now() 
    stoptime = starttime + datetime.timedelta(0,5)
    async for sample in sdr.stream():
        if datetime.datetime.now() > stoptime:
            raise StopAsyncIteration 
        else:
            print(sample)       
    return

def printme():
    print("here now")

asyncio.run(main())
printme()

Currently, the output ends like this:

[-0.05882353+0.12941176j -0.01960784-0.03529412j -0.15294118-0.1372549j
 ... -0.09803922+0.04313725j  0.06666667+0.02745098j
  0.02745098-0.04313725j]
[ 0.01960784+0.0745098j   0.08235294-0.12941176j  0.14509804-0.23137255j
 ...  0.11372549-0.03529412j  0.03529412+0.02745098j
 -0.02745098-0.15294118j]

and just sits there.

I understand this is not a minimum working sample since it cannot be copied and run by everyone, but that's also because I'm having trouble substituting something simple for the data stream. I hope I'm still getting the point across. I've tried using await asyncio.wait_for, but I haven't figured that out, either. I'm not familiar with async operations. Any help would be appreciated, thank you in advance!

0

There are 0 best solutions below