Can an asyncio event loop run in the background without suspending the Python interpreter?

前端 未结 2 421
孤独总比滥情好
孤独总比滥情好 2020-12-01 03:50

The documentation for asyncio gives two examples for how to print \"Hello World\" every two seconds: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-w

2条回答
  •  旧时难觅i
    2020-12-01 04:23

    With Python 3.8, you can use the new asyncio REPL.

    $ python -m asyncio
    >>> async def greet_every_two_seconds():
    ...     while True:
    ...         print('Hello World')
    ...         await asyncio.sleep(2)
    ...
    >>> # run in main thread (Ctrl+C to cancel)
    >>> await greet_every_two_seconds()
    ...
    >>> # run in background
    >>> asyncio.create_task(greet_every_two_seconds())
    

提交回复
热议问题