Search code examples
pythonmultithreadingtimeeval

Is it possible to cancel an exec() in python after 5 seconds


I am working on a python script that runs small user generated scripts. There is a problem though when a user submits a script that infinitely loops. I was wondering if it would be possible to stop an exec() after 5 seconds of running.

x = exec(user_code)
 delay(5)
 x.cancel()

something like this ^

So far I tried using threading but the results were mixed. I threaded a function called main which would run their code through exec then I would delete the thread after 5 seconds but it was buggy.


Solution

  • You could use multiprocessing:

    import multiprocessing
    import time
    
    def exec(n):
        for i in range(10000 * n):
            print("Whatever") #Your code
    
    if __name__ == '__main__':
        process = multiprocessing.Process(target=exec, name="Exec", args=(10,))
        process.start()
        time.sleep(1) #How much to wait
        process.terminate()
        process.join()