Python Tricks

Abstract A collection of Python tricks and tips that I've collected from around the 'net.

Instant Web Server

From Kevin Altis' blog: Just cd to a directory with some HTML you want to test, and run:

user$ python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"

Point a web browser at localhost:8000, and away you go.

Where In The Code Am I?

def _functionId(nFramesUp): """ Create a string naming the function n frames up on the stack.""" co = sys._getframe(nFramesUp+1).f_code return "%s (%s @ %d)" % (co.co_name, co.co_filename, co.co_firstlineno) def notYetImplemented(): """ Call this function to indicate that a method isn't implemented yet.""" raise Exception("Not yet implemented: %s" % _functionId(1)) #... def complicatedFunctionFromTheFuture(): notYetImplemented()

Timeout a Function

This TimeoutFunction class lets you assign a timeout value to an arbitrary function. It's from John P. Speno's Pythonic Avocado.

class TimeoutFunctionException(Exception): """Exception to raise on a timeout""" pass class TimeoutFunction: def __init__(self, function, timeout): self.timeout = timeout self.function = function def handle_timeout(self, signum, frame): raise TimeoutFunctionException() def __call__(self, *args): old = signal.signal(signal.SIGALRM, self.handle_timeout) signal.alarm(self.timeout) try: result = self.function(*args) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result if __name__ == '__main__': import sys stdin_read = TimeoutFunction(sys.stdin.readline, 1) try: line = stdin_read() except TimeoutFunctionException: print 'Too slow!' else: print 'You made it!'