Locating source for any Python module

By Chris Lamb

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
$ 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
$ ls subprocess.py

Chris Lamb is a freelance software developer and the current Debian Project Leader. You can read other posts by me, see software I have written or read more about me. You can also follow me @lolamby.

Tags: Hacks GNU/Linux

Planets: WUGLUG UWCS Debian ALUG

Thursday 22nd April 2010

Five comments