Which Python?

Finding packages, modules, and entry points.

which is a handy utility for discovering the location of executables in your shell; it prints the full path to the first executable on your $PATH with the given name:

$ which python
/usr/local/bin/python

In a similar stream, I often want to know the location of a Python package or module that I am importing, or what entry points are available in the current environment.

Lets write a few tools which do just that.


whichpy:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python

import os
import sys

if len(sys.argv) < 2:
    exit(1)

try:
    mod = __import__(sys.argv[1], fromlist=['.'])
except ImportError:
    exit(1)

path = mod.__file__
if path.endswith('.pyc'):
    path = path[:-1]
if os.path.splitext(path)[0].endswith('__init__'):
    path = os.path.dirname(path)
print path

This script will print out the file path (or directory path if a package) of the named python import. E.g.:

$ whichpy nose
/usr/local/lib/python2.7/site-packages/nose

$ whichpy os.path
/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py

whichep:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/usr/bin/env python

import argparse
import pkg_resources

parser = argparse.ArgumentParser()
parser.add_argument('group')
parser.add_argument('name', nargs='?')
args = parser.parse_args()

for ep in pkg_resources.iter_entry_points(args.group, args.name):
    print ep

Even shorter, this script will print out the entry points in the given group (filtering by name if provided). E.g.:

$ whichep console_scripts
pip = pip:main
nosetests = nose:run_exit
easy_install = setuptools.command.easy_install:main
virtualenv = virtualenv:main

$ whichep setuptools.installation
eggsecutable = setuptools.command.easy_install:bootstrap
Posted . Categories: .