Trying to understand python
Код: Выделить всё
asyncioКод: Выделить всё
concurrent.futuresКод: Выделить всё
#!/usr/bin/env python3 # encoding: utf-8 """Sample script to test asyncio functionality.""" import asyncio import logging from time import sleep # noqa logging.basicConfig(format='%(asctime)s | %(levelname)s: %(message)s', level=logging.INFO) async def wait(i: int) -> None: """The main function to run asynchronously""" logging.info(msg=f'Entering wait {i}') await asyncio.sleep(5) logging.info(msg=f'Leaving wait {i}') # This does not show because all pending tasks are SIGKILLed? async def main() -> None: """The main.""" [asyncio.create_task( coro=wait(i)) for i in range(10)] logging.info(msg='Created tasks, waiting before await.') sleep(5) # This is meant to verify the tasks do not start by the create_task call. # What changes after the sleep command, i.e. here? # If the tasks did not start before the sleep, why would they start after the sleep? if __name__ == '__main__': asyncio.run(main=main()) Код: Выделить всё
2023-05-03 12:30:45,297 | INFO: Created tasks, waiting before await. 2023-05-03 12:30:50,302 | INFO: Entering wait 0 2023-05-03 12:30:50,304 | INFO: Entering wait 1 2023-05-03 12:30:50,304 | INFO: Entering wait 2 2023-05-03 12:30:50,304 | INFO: Entering wait 3 2023-05-03 12:30:50,304 | INFO: Entering wait 4 2023-05-03 12:30:50,304 | INFO: Entering wait 5 2023-05-03 12:30:50,304 | INFO: Entering wait 6 2023-05-03 12:30:50,304 | INFO: Entering wait 7 2023-05-03 12:30:50,304 | INFO: Entering wait 8 2023-05-03 12:30:50,304 | INFO: Entering wait 9 - What exactly is triggering the async task here (which just logs two lines at the console upon entry and exit)? Clearly, creating the tasks is not really making them run, as I am waiting for long enough after creating them in main. Even the timestamps show they are run after the blocking sleep in main. Yet, just as the main function seems to finish its sleep, and exit, the tasks seem to be triggered. Should not the main thread just exit at this point?
Код: Выделить всё
wait - The exit log is never printed (commented in the code). Does it mean the subprocess are just started after the main thread exits, and then immediately killed?
Источник: https://stackoverflow.com/questions/761 ... ncio-tasks