I have the following code:
import asyncio
import time
class displayName:
def __init__(self, name, delay, exit = False):
self.name = name
self.delay = delay
self.exit = exit
async def start(self):
#displays name of object at regular time intervals
self.exit = False
print('starting display program...')
while True:
if self.exit == True:
print('ending display program')
break
print(self.name)
await asyncio.sleep(self.delay)
async def stop(self):
await asyncio.sleep(0)
self.exit = True
async def update_name(self, name):
await asyncio.sleep(0)
self.name = name
async def update_delay(self, delay):
await asyncio.sleep(0)
self.delay = delay
Normally, I would execute:
display = displayName('Tom',5)
loop = asyncio.get_event_loop()
loop.create_task(display.start())
and if I wanted to change the name being displayed I would execute:
loop.create_task(display.update_name('Jerry'))
and to stop the loop I would execute:
loop.create_task(display.stop())
which changes display.exit to True and ends the loop.
However, if I attempt to execute this code using:
asyncio.run(display.start())
then I cannot get the loop to close!
I've tried:
loop1 = asyncio.get_running_loop()
loop1.close()
and this did nothing. I can do a keyboard interrupt, but any time I try to run another task with asyncio.run(), I get an error message saying that asyncio.run() cannot be called from a running event loop!
How do I close this active loop so that I can use asyncio.run() again??!!!
I am working in a Jupyter Notebook, if this is relevant.