Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtualenv keeps loading global site packages on Windows

I've looked around on SO, and the answers I have found to my problem haven't allowed me to solve it yet.

I want to use isolated virtualenv environments, but for one reason or another, virtualenv keeps loading global site packages, when in django's shell...

I tried to clean up PATH variables, until only c:\Python26\Scripts and c:\Python26 remain. I then create my environment.

virtualenv --distribute --no-site-packages myproject

I then activate the virtualenv. PATH is now (irrelevant vars scrapped):

PATH=E:\Development\django_projects\myproject\Scripts;C:\Panda3D-1.7.0\python;C:\Panda3D-1.7.0\bin;c:\python26\Scripts;

PYTHONPATH=C:\Panda3D-1.7.0\

So far, so good. I launch python...

>>> import django
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ImportError: No module named django

Let's just try a module I'm sure is in my c:\python site-packages directory.

>>> import BeautifulSoup
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named BeautifulSoup

Yay! No global site packages! On to the next one then. From the command prompt, I type:

django-admin.py

And it works! But wait... I haven't installed Django yet. How is this possible?

After this, it gets even weirder... I first add these to virtualenv's activate.bat script so that Django can find my settings.

set PYTHONPATH=E:\Development\django_projects\myproject\
set DJANGO_SETTINGS_MODULE=settings.development

Now I launch django-admin.py shell and

In [1]: import BeautifulSoup
In [2]: BeautifulSoup.__file__
Out[2]: 'C:\\Python26\\lib\\site-packages\\BeautifulSoup.pyc'

How is this even possible?

Flash of insight

While typing this, I suddenly get it. .py is a file extension coupled with my c:\python26\python.exe executable, instead of the virtualenv one!

python manage.py
Traceback (most recent call last):
  File "manage.py", line 2, in <module>
    from django.core.management import execute_manager
ImportError: No module named django.core.management

Heh. Anyone has any idea of how to couple the .py file extension to my virtualenv's python executable instead of the system defined python executable?

like image 215
LaundroMat Avatar asked Nov 06 '10 10:11

LaundroMat


1 Answers

A little bit of extra .bat hackery can easily fix this. My standard additions to activate.bat are:

REM custom venv settings
set PYTHONPATH=%\VIRTUAL_ENV%;%\VIRTUAL_ENV%\conf;%\VIRTUAL_ENV%\apps
set DJANGO_SETTINGS_MODULE=settings

ftype Python.File=%VIRTUAL_ENV%\Scripts\python.exe %1 %*

and to deactivate.bat

REM restore ftype
ftype Python.File=C:\tools\Python27\python.exe %1 %*
like image 60
m0nonoke Avatar answered Oct 22 '22 00:10

m0nonoke