2017-07-06 62 views
3

是有办法的时间限制oparations在python,如:操作时间限制

try: 
    cmds.file(file, o=1, pmt=0) 
except: 
    print "Sorry, run out of time" 
    pass 

回答

1

如果你在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发送)当这样提出了一个自定义异常。你当然可以调整时间限制。

+0

不幸的是我在Windows上,但我认为我可以用它赢得太 https://docs.python.org/2/library/signal.html –

+0

如果'cmds.file()'是你想要的到时候,你的运气不好 - 它阻塞了主线程,即使你的计时器在第二个线程上正常启动,你也不会有非崩溃的方式来取消操作。对于'cmds.file',我认为你唯一的选择可能是启动一个maya实例是一个子进程,然后在子进程超时时完全终止它。 – theodox