Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operation time limit

Tags:

python

maya

is there a way to time limit the oparations in python, eg:

try:
    cmds.file( file, o=1, pmt=0 )
except:
    print "Sorry, run out of time"
    pass
like image 276
Jozef Plata Avatar asked Apr 24 '26 21:04

Jozef Plata


1 Answers

If you're on Mac or a Unix-based system, you can use signal.SIGALRM to forcibly time out functions that take too long, so your code would look like:

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

Basically, you're creating a custom exception that's raised when the after the time limit is up (i.e., the SIGALRM is sent). You can of course tweak the time limit.

like image 188
Auden Young Avatar answered Apr 26 '26 11:04

Auden Young