I'm from a .NET background, but I notice that asyncio
behaves differently to async
and await
in .NET:
I'm trying to achieve the following:
a
) that does some computeb
) that waits for user input to quitb
(user has quitted)a
The following does not execute task a
at all:
processing = asyncio.create_task(do_processing())
user_finished = asyncio.create_task(stdin_listener())
await user_finished
processing.cancel()
The reason I understand is because processing
is never awaited, however if I await this task, it will never return because it will never reach the cancel()
.
I've had a look through the docs, and can't find this simple example, or been able to piece this together. Just not familiar with this API, so please enlighten me.
Edit: I've discovered that the handling of tasks above is correct. However, in the method stdin_listener()
, I have a call to:
input("Press Q to quit\n")
which is blocking. I'm going to look into other approaches to this call.
I've decided to use SIGINT to close out:
exiting = False
async def do_processing():
global exiting
while not exiting:
await asyncio.sleep(1)
# do processing here
def handler(signal_received, frame):
global exiting
# Handle any cleanup here
print('SIGINT or CTRL-C detected. Exiting gracefully')
exiting = True
signal(SIGINT, handler)
await asyncio.create_task(do_processing())
# post processing
Link to further explanation: https://www.devdungeon.com/content/python-catch-sigint-ctrl-c
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.