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

时间:2018-07-31 16:39:49

标签: python exec eval

如果执行时间太长,我想停止执行exec或eval命令。我知道如何使用多重处理来实现,但是我想知道是否有更简单的解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

即使您说可以,但是这是我的解决方案:

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