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?
1 Answer
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 2 Comments
yyy
Wow, thanks! You're solution is better than the way I did it with multiprocessing. I can almost use that if only I figure out how to get the text that exec() prints out to the console while being run using apply_async.
yyy
Update: Found out how to get the console's output - the same as suggested here: stackoverflow.com/questions/3906232/… but put the "with stdoutIO() as s: exec(code)" line inside another function and call it with apply_async instead of exec.
signalto interrupt the main thread—unless the code that you’reexecing could change the signal handlers. Butmultiprocessingis probably a better solution, and not significantly more complicated.with quit_after_seconds(30):