Search code examples
pythonexeceval

Is it possible to stop exec or eval in Python after a certain amount of time?


I want to stop the execution of the exec or eval commands if they take too long to complete. I know how to do it using multiprocessing but I was wondering if there's an easier solution. Any ideas?


Solution

  • Even though you said you can do it, here's my solution:

    #!/usr/bin/env python3
    """Context manager to limit execution time."""
    
    import multiprocessing
    import time
    from typing import Callable
    
    
    def run_until(seconds: int, func: Callable, *args) -> None:
        """Run a function until timeout in seconds reached."""
        with multiprocessing.Pool(processes=2) as pool:
            result = pool.apply_async(func, [(*args)])
            try:
                result.get(timeout=seconds)
            except multiprocessing.TimeoutError:
                pass
    
    
    if __name__ == "__main__":
        run_until(1, time.sleep, 20) # exits after 1 second