tags:

views:

92

answers:

2

In *nix systems one can use which to find out the full path to a command. For example:

$ which python
/usr/bin/python

or whereis to show all possible locations for a given command

$ whereis python
python: /bin/python.exe /bin/python2.5-config /usr/bin/python.exe /usr/bin/python2.5-config /lib/python2.4 /lib/python2.5 /usr/lib/python2.4 /usr/lib/python2.5 /usr/include/python2.4 /usr/include/python2.5 /usr/share/man/man1/python.1

Is there an easy way to find out the location of a module in the PYTHONPATH. Something like:

>>> which (sys)
'c:\\Python25\Lib\site-packages'
+5  A: 

If you do:

modulename.__file__

You will get a full path return of that exact module. For example, importing django:

>>>> import django
>>> django.__file__
'/home/bartek/.virtualenvs/safetyville/lib/python2.6/site-packages/django/__init__.pyc'

Edit: I recommend seeing the comments below for some good insight if you haven't had a chance to.

Bartek
Is it guaranteed that every module has the `__file__` attribute?for example: ` >>> import sys >>> sys.__file__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute '__file__' >>> import os >>> os.__file__ 'C:\\Python25\\lib\\os.pyc'`
bgbg
+1 Although this doesn't seem to work for `sys` as in the OP's example
Mike Dinsdale
It doesn't work for `sys` because `sys` doesn't come from a file at all: it's a built-in module. As such there is no sensible answer to `which(sys)`.
bobince
A: 

This is a bit kludgy but you can type python pywhich os django PIL:

import os, os.path
import sys

def pywhich(mod):
    for p in sys.path:
        try:
            if any(p.startswith(mod + '.py') for p in os.listdir(p)):
                return os.path.join(p, mod)
        except OSError:
            pass
    return "Not found"

if __name__ == '__main__':
    for arg in sys.argv[1:]:
        print arg, pywhich(arg)
hughdbrown