简体   繁体   English

如果需要太长时间,如何终止 python 中的 exec() function?

[英]How to terminate exec() function in python if it takes too long?

I am trying to make a function that takes in user's code and runs it:我正在尝试制作一个接收用户代码并运行它的 function:

code = input("Your code: ")

def execute(c):
    exec(c)
    
execute(code)

However, if the user enters in an infinite loop, the function runs forever.但是,如果用户进入无限循环,function 将永远运行。

Is there a way to terminate the exec() function if the function takes too long?如果 function 花费的时间太长,有没有办法终止exec() function? For example, if the code takes longer than 15 seconds to execute, the programme terminates.例如,如果代码执行时间超过 15 秒,则程序终止。

Thanks in advance.提前致谢。

There are multiple solutions, For example you could pass a global variable stop condition and raise exception from inside the exec once condition has met.有多种解决方案,例如,您可以传递全局变量停止条件,并在满足条件后从 exec 内部引发异常。 Other solution would be to run exec in a separate thread/process and sending some stop signal once desired.其他解决方案是在单独的线程/进程中运行 exec 并在需要时发送一些停止信号。

You can use wrapt_timeout_decorator您可以使用wrapt_timeout_decorator

from wrapt_timeout_decorator import *

@timeout(15)
def execute(c):
    exec(c)

code = input("Your code: ")
execute(code)

This will throw an exception if the function takes more than 15 sec to finish - TimeoutError: Function execute timed out after 15.0 seconds如果 function 需要超过 15 秒才能完成,这将引发异常 - TimeoutError: Function execute timed out after 15.0 seconds

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM