Python Cheat Sheet

I like to solve my problems in python, so here is a small cheat sheet on python tricks that make my life easier.

There’s not much yet, but more to come!

End for loop on return-key hit

If you need a certain task done over and over again, you can use watch -n [seconds] 'task', but I sometimes need all the information at once without a clear page after every execution. That’s where python comes in handy.

#!/usr/bin/python
import sys, select

print "Hit <Return> to exit"
while True:
	print "I'm doing stuff :)"
	if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        print "Exiting..."
        break

This little snippet will do what you want until the end of (up)time – or until you hit the return button.

HTTP requests made easy

Normally Python uses urllib to make HTTP request, but that’s kind of a PITA and not very pythonic. “requests” is a library that aims to make it easier – and it does!

Everything you need to know to get started can be found here

It’s easy to install

git clone git://github.com/kennethreitz/requests.git
cd folder
sudo python setup.py install

and easy to use

>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}

Manipulating strings

There is one thing that baffled me when it comes to strings in python.
Namely, I wanted to print the two middle characters of a string. This is how it’s done

	# My string (I want to print "CD")
	>>> string = "ABCDEF"
    # get half the length of the string (string == 6, half ==3)
    >>> pos = len(string)/2
    # print the middle chars.
    >>> print string[pos:pos+1]
    C

Note: pos == 3, pos+1 == 4
To my understanding, pos and pos+1 shoudl print character 3 and 4, meaning CD. Python however sees positions as pointers to the chars meaning pos+1 points to the beginning of the 4th char. Therefore the 4th character D is not printed. To get both, you need to specify the start of the 5th character, as this is also the end of the 4th.

The correct syntax to print CD would be

>>> print string[pos:pos+2]
CD

For more string manipulation, look here.