是否可以在一定时间后停止 Python 中的 exec 或 eval?

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

我想停止执行 exec 或 eval 命令,如果它们需要很长时间才能完成。我知道如何使用多处理来做到这一点,但我想知道是否有更简单的解决方案。有什么想法吗?

虽然你说你可以做到,但这是我的解决方案:

#!/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