有没有办法在 python 中限制时间,例如:
try:
cmds.file( file, o=1, pmt=0 )
except:
print "Sorry, run out of time"
pass
最佳答案
如果您使用的是 Mac 或基于 Unix 的系统,您可以使用 signal.SIGALRM
强制使耗时过长的函数超时,因此您的代码如下所示:
import signal
class TimeoutException(Exception): # custom exception
pass
def timeout_handler(signum, frame): # raises exception when signal sent
raise TimeoutException
# Makes it so that when SIGALRM signal sent, it calls the function timeout_handler, which raises your exception
signal.signal(signal.SIGALRM, timeout_handler)
# Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
signal.alarm(5)
try:
cmds.file( file, o=1, pmt=0 )
except TimeoutException:
print "Sorry, run out of time" # you don't need pass because that's in the exception definition
基本上,您正在创建一个自定义异常,该异常会在时间限制结束后引发(即发送 SIGALRM
)。您当然可以调整时间限制。
关于python - 操作时限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44952761/