Why doesn't virtualenv on Windows associate .py/.pyw/.pyo/.pyc files with virtualenv's version of Python executables? Why doesn't virtualenv on Windows associate .py/.pyw/.pyo/.pyc files with virtualenv's version of Python executables? windows windows

Why doesn't virtualenv on Windows associate .py/.pyw/.pyo/.pyc files with virtualenv's version of Python executables?


File type associations are handled in the Windows registry. The virtualenv activate script would have to modify the registry keys and the deactivate script would need to restore the previous value (or risk breaking the associations).

What happens if you activate a virtualenv, open a second instance of cmd.exe, and activate a different virtualenv? Unless you deactivate them in the right order, the stored values for the registry keys would be lost.

I'm not a virtualenv developer, I'd say that the potential problems far outweigh the slight benefit.


virtualenvwrapper-win does associate Python files with currently active virtualenv:

Note that the batch script pyassoc requires an elevated command prompt or that UAC is disabled. This script associates .py files with python.bat, a simple batch file that calls the right python.exe based on whether you have an active virtualenv. This allows you to call python scripts from the command line and have the right python interpreter invoked. Take a look at the source -- it's incredibly simple but the best way I've found to handle conditional association of a file extension.

python.bat looks like this

@echo offif defined PYTHONHOME (    goto MAIN)FOR /F "tokens=*" %%i in ('whereis.bat python.exe') do set PYTHONHOME=%%~dpiSET PYTHONHOME=%PYTHONHOME:~0,-1%:MAINSETLOCAL EnableDelayedExpansionif defined VIRTUAL_ENV (    set PY="%VIRTUAL_ENV%\Scripts\python.exe") else (    set PY="%PYTHONHOME%\python.exe")ENDLOCAL & %PY% %*:END

UPDATE

Now it's possible – see How to associate Python scripts with active virtualenv?


All of my Python development at present is on Linux, but I'm looking at working on Windows, which is how I found this question. My answer would be an operational one:

Instead of typing <scriptName>.py at a prompt, I always type python <scriptName>.py. If you adopt this habit, won't virtualenv execute the proper Python for you?