April 22nd 2010

Locating source for any Python module

When I'm too lazy to find API documentation I just read the source code. To make this slightly easier in Python, here's what I use in my ~/.${SHELL}rc:

cdp () {
  cd "$(python -c "import os.path as _, ${1}; \
    print _.dirname(_.realpath(${1}.__file__[:-1]))"
  )"
}

For packages, this takes you to the corresponding source directory:

$ cdp twisted.web
$ pwd
/usr/share/pyshared/twisted/web
$ ls
_auth/  domhelpers.py  html.py  iweb.py  resource.py
[..]

The realpath and [:-1] hackery follow any python-support symlinks. For "standalone" .py (or .so) modules, cdp will take you to the directory it resides in:

$ cdp subprocess
$ pwd
/usr/lib/python2.5
$ ls subprocess.py
subprocess.py



You can subscribe to new posts via email or RSS.