2010-04-13 10 views
6

Nei sistemi * nix si può usare which per trovare il percorso completo di un comando. Per esempio:Python analog of Unix 'which'

$ which python 
/usr/bin/python 

o whereis per mostrare tutte le posizioni possibili per un dato comando

$ 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 

C'è un modo semplice per scoprire la posizione di un modulo nel PYTHONPATH. Qualcosa di simile:

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

risposta

5

Se lo fai:

modulename.__file__

Si otterrà un ritorno percorso completo di quel modulo esatto. Ad esempio, django importazione:

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

Edit: Vi consiglio di vedere i commenti qui sotto per qualche buona intuizione se non avete avuto la possibilità di.

+2

E' garantito che ogni modulo ha la '__file__' attributo? per esempio: 'sys >>> >>> importazione sys .__ FILE__ Traceback (chiamata più recente scorso): file "", linea 1, in AttributeError: 'modulo' oggetto non ha l'attributo ' __FILE__' os >>> import >>> os .__ FILE__ 'C: \\ Python25 \\ lib \\ os.pyc' ' –

+0

+1 Anche se questo non sembra funzionare per' sys' come nell'esempio dell'op –

+3

Non funziona per 'sys' perché' sys' non proviene affatto da un file: è un modulo built-in. In quanto tale, non esiste una risposta sensata a "quale (sys)". – bobince

1

Questo è un po 'kludgy ma è possibile digitare 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)