A script to quickly access the source of installed python packages

10 July 2013

It is sometimes useful to access the source of an external Python package in your current virtualenv, for example to inspect its code or to place breakpoints while debugging.

If you use virtualenv_wrapper then you may use the cdsitepackages command. However, this doesn't help much for packages that have been installed in "editable" mode (that is, typically in the <virtualenvpath>/src/ folder).

So I wrote a little bash & zshell script to quickly access any package, regardless of where they are installed in your virtualenv. This script also allows tab completion to make things even faster:

(myenv)$ goto <TAB>
admin_tools      curses           encodings        feincmstools     lib2to3          paramiko         ratelimit
appconf          dateutil         example          gargoyle         logging          password_reset   requests
bsddb            debug_toolbar    example_module   gunicorn         markdown         PIL              setuptools
compiler         distutils        example_project  hotshot          modeldict        pip              sorl
compressor       django           fabfile          idlelib          mptt             psycopg2         south
ctypes           email            feincms          jsonfield        nexus            pyrepl

(myenv)$ goto d<TAB>
dateutil       debug_toolbar  distutils      django

(myenv)$ goto django
(myenv)$ pwd

Here's the source:

# Author: Julien Phalip
# License: BSD
# Description: Change the current directory to the path of the given Python package.

function goto {
    cd `python -c "import pkgutil; print(pkgutil.get_loader('$1').filename)"`

function _top_level_packages {
    python -c "import pkgutil; print('\n'.join([name for loader, name, ispkg in sorted(pkgutil.iter_modules()) if ispkg]))"

if [ -n "$BASH" ] ; then
    _goto_complete () {
        local cur="${COMP_WORDS[COMP_CWORD]}"
        COMPREPLY=( $(compgen -W "`_top_level_packages`" -- ${cur}) )
    complete -o default -o nospace -F _goto_complete goto
elif [ -n "$ZSH_VERSION" ] ; then
    _goto_complete () {
        reply=( $(_top_level_packages) )
    compctl -K _goto_complete goto

To install this script in your user's bin/ folder, simply run the following:

(myenv)$ mkdir -p ~/bin/
(myenv)$ wget https://gist.github.com/jphalip/5967635/raw/goto.sh -P ~/bin/
(myenv)$ source ~/bin/goto.sh

To make this script accessible in all future terminal sessions, simply add source ~/bin/goto.sh to your user's bash or zshell profile.

PS: Thanks to Carlos Nepomuceno for providing some useful tips about pkgutil on the Python users mailing list.