Python 2 and useful notes

virtualenv

Use the Python interpreter of your choice

$ virtualenv -p /usr/bin/python2.7 venv

or change the interpreter globally with an env variable in ~/.bashrc:

$ export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python2.7

Using the venv

To begin using the virtual environment, it needs to be activated:

$ source venv/bin/activate

The name of the current virtual environment will now appear on the left of the prompt (e.g. (venv) Your-Computer:your_project UserName$) to let you know that it’s active. From now on, any package that you install using pip will be placed in the venv folder, isolated from the global Python installation.

Install packages as usual, for example:

$ pip install requests

Deactivate venv

If you are done working in the virtual environment for the moment, you can deactivate it:

$ deactivate

This puts you back to the system’s default Python interpreter with all its installed libraries.

Delete venv

To delete a virtual environment, just delete its folder. (In this case, it would be rm -rf venv.)

pprint

In Python is pretty useful to find out what variables are set here.

pprint(vars())

requests library

Debugging through Logging

import requests
import logging

try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client

http_client.HTTPConnection.debuglevel = 1
# You must initialize logging, otherwise you'll not see debug output.

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

Requests use httplib in its underlying infrastructure. You can set logging to be verbose and to apply logging for httplib.

json.tool

Python JSON validator tool that can be used from the command line python -m json.tool