Question

How to terminate a function which is working in python?

I want to make a code which works like this: after certain seconds I want to terminate the working function in the main function.

I've tried the below code but when the code in the loop function isn't an async function(like await asyncio.sleep(1)) it doesn't work.

import asyncio

async def loop():
    while True:
        pass


async def main():
    task = asyncio.Task(loop())
    await asyncio.sleep(3)
    print('1223')
    task.cancel()
    print('x')

asyncio.run(main())
 3  91  3
1 Jan 1970

Solution

 2

Use multiprocessing. When you want a function to be terminated after certain seconds, then all the function should start running simultaneously. My comments inside the code explains the rest.

import multiprocessing as mp
import time as t

# function which needs to be terminated after certain seconds
def func1():
  # Do something
  
def func2():
  # Do something

# A function to terminate func1      
def stop(func):

    # terminate the func after 1 sec
    t.sleep(1)
    
    func.terminate()


# Add execution guard in case "spawn"-multiprocessing mode is used
if __name__ == "__main__":

    # Create two processes
    pro_1 = mp.Process(target=func1)
    pro_2 = mp.Process(target=func2)
    
    # third process being stop() and the args being pro_1
    pro_3 = mp.Process(target=stop, args=(pro_1,))
    
    # Start the processes
    pro_1.start()
    pro_2.start()
    pro_3.start()
    
    
    
    #As the pro_1 is terminated use process.join for only pro_2 and pro_3
    pro_2.join()
    pro_3.join()
2024-07-11
Suramuthu R