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

§

Tags: Computer GNU/Linux Hacks
Planets: ALUG UWCS WUGLUG Debian

§

Five comments

  1. This is a really sweet command, very very nice!

    Michael Nielson

  2. Why not use ipython?

    import subprocess
    subprocess??

    Jose Arthur Benetasso Villanova

    That doesn't work so well for packages (try with "email") and I would prefer to use grep than search inside a pager. Also, more typing.

    lamby

  3. I'd use imp.find_module to find the location over explicitly importing it, but that's just personal preference.

    Jason Scheirer

  4. So cool and so useful. Many thanks for the knowledge, many, many thanks.

    Daniel

  5. Quite a few Django modules fail on import, here is a version that uses imp instead of import

    cdp () {
    cd "$(python -c "import sys, imp, os
    path = sys.path
    for i in '${1}'.split('.'): path = [imp.find_module(i,path)[1],]
    path = path[0] if os.path.isdir(path[0]) else os.path.dirname(path[0])
    print path")"
    }

    Michael Nielson

Reply

§