import asyncio import signal async def shutdown(sig, loop): """Shutdown signal""" print(f"Received signal {sig.name}...") tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()] [task.cancel() for task in tasks] print(f"Cancelling {len(tasks)} outstanding tasks") await asyncio.gather(*tasks, return_exceptions=True) loop.stop() async def run_managed_subprocess(): # 1. Start the process proc = await asyncio.create_subprocess_exec( "sleep", "300", stdout=asyncio.subprocess.PIPE ) try: # 2. Wait for it (this is where cancellation will trigger) stdout, stderr = await proc.communicate() except asyncio.CancelledError: # 3. Handle cancellation: KILL THE PROCESS print("Task cancelled, terminating subprocess...") try: print("Поймали !") proc.terminate() # It is best practice to wait for it to actually exit await proc.wait() except ProcessLookupError: pass # Already gone raise # Re-raise to complete the cancellation # get current loop loop = asyncio.get_event_loop() # add handler loop.add_signal_handler( signal.SIGTERM, lambda: asyncio.create_task(shutdown(signal.SIGTERM, loop)) ) loop.run_until_complete(run_managed_subprocess())