Python Tricks

Nick Vargish

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?

From Ned Batchelder's blog, a Python version of the well-known __FILE__ and __LINE__ macros from C compilers:
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():

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""" 

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) 
            result = self.function(*args)
            signal.signal(signal.SIGALRM, old)
        return result 

if __name__ == '__main__': 
    import sys
    stdin_read = TimeoutFunction(sys.stdin.readline, 1) 
        line = stdin_read() 
    except TimeoutFunctionException: 
        print 'Too slow!' 
        print 'You made it!'

Last modified: 14 October 2004