简体   繁体   中英

How to run a task in the background until user inputs?

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:

  1. Start a task ( a ) that does some compute
  2. Start a task ( b ) that waits for user input to quit
  3. await task b (user has quitted)
  4. cancel task 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM