Python

Allow environment to determine python shebang path

The following will exectute the system-wide python normally, or a virtual env python if you happen to have one sourced.

#!/usr/bin/env python

Iterating and enumerating on ordered dicts

Iterating with counter over items:

        for i, (key, value) in enumerate(ordereddict.items()):
            print i, key, value

Iterating with counter over keys:

        for i, key in enumerate(ordereddict.iterkeys()):
            print i, key

Iterating with counter over values:

        for i, value in enumerate(ordereddict.itervalues()):
            print i, value

Reading a single character from stdin

Why there isn't an easier way of doing this, I have no idea. It'd be nice if this would work:

sys.stdin.read(1)

...however, because the file is a tty, nothing gets read until the user hits enter.

Enter getch. It's a utility written by Danny Yoo and stolen from a posting I found on google: ASPN : Python Cookbook : getch()-like unbuffered character reading from stdin on both Windows and Unix.

Description:

Paging output

Let Python determine the best pager available:

import pydoc
pydoc.pager(text)

This may pipe the text into an external program like less or more.

...or explicitly use the built-in pager:

import pydoc
pydoc.ttypager(text)

Source: http://www.velocityreviews.com/forums/t584112-paging-in-python-shell.html

Lambda function array manipulation

A fun bit of code brought to my attention by Lih:

>>> l = [1,2,3,4]
>>> l
[1, 2, 3, 4]
>>> l2 = [ x+1 for x in l ]
>>> l2
[2, 3, 4, 5]

Syndicate content