[pyar] Odio el sys.path

Alejandro Santos listas en alejolp.com
Vie Mar 18 20:37:03 ART 2011


On Fri, Mar 18, 2011 at 1:24 PM, Manuel Kaufmann <humitos en gmail.com> wrote:
> ¡Porque no lo entiendo!
>

Cuando hacés "import antigravity" la funcion "__import__" es la que
importa el modulo, lo carga en memoria y devuelve la referencia al
modulo. Basicamente lo hace recorriendo la lista "sys.path" de
izquierda a derecha intentando encontrar el modulo que querés
importar.

>
> import sys
>
> if 'lib' not in sys.path:
>    # Add /lib as primary libraries directory, with fallback to /distlib
>    # and optionally to distlib loaded using zipimport.
>    sys.path[0:0] = ['lib', 'distlib', 'distlib.zip']
>

Eso agrega cuatro rutas más al principio del path. Ahi hay dos problemas:

1) El item cero deberia ser siempre el path desde donde se inició la
aplicación. Conviene cambiar sys.path[0:0] por sys.path[1:1].

2) Las rutas son relativas al modulo desde donde haces "import",
deberias cambiar las rutas para que sean absolutas. En tu caso, si
querés importar algo que está dentro de "lib" desde el modulo
"apps.busstopped.filters" va a tirar ImportError.

Para convertir todas las rutas en absolutas podes hacer algo asi:

> if 'lib' not in sys.path:
>    import os
>    PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
>    # Add /lib as primary libraries directory, with fallback to /distlib
>    # and optionally to distlib loaded using zipimport.
>    sys.path[0:0] = [PROJECT_ROOT + '/lib', PROJECT_ROOT + '/distlib', PROJECT_ROOT + '/distlib.zip']
>

>
> File "/home/humitos/busstopped/busstopped/busstopped-gae/apps/busstopped/utils.py",
> line 4, in <module>
>    from apps.busstopped.models import Holiday
>
> ImportError: cannot import name Holiday
>

No lo encuentra porque
"/home/humitos/busstopped/busstopped/busstopped-gae" no está en
sys.path.

Como un hack de viernes por la noche probá hacer:

> if 'lib' not in sys.path:
>    # Add /lib as primary libraries directory, with fallback to /distlib
>    # and optionally to distlib loaded using zipimport.
>    sys.path[1:1] = ['lib', 'distlib', 'distlib.zip']

Y si no anda con eso entonces:

>    sys.path.insert(1, "/home/humitos/busstopped/busstopped/busstopped-gae")
>

Saludos,

-- 
Alejandro Santos
http://alejolp.com.ar



More information about the pyar mailing list