Installing PyWin32 in a Virtual Environment

I had to figure this out recently, so I thought I’d share (assumes you’re running 64-bit Python 2.7, if either assumption is false, the modifications should be obvious):

  1. Create a new virtual environment
    PS C:\scratch> virtualenv testenv
    New python executable in testenv\Scripts\python.exe
    Installing setuptools, pip...done.
  2. Get the python path from the registry and save it
    PS C:\scratch> $oldLocation = (get-itemproperty -path HKLM:\SOFTWARE\Python\PythonCore\2.7\InstallPath\ -name '(Default').'(Default)'
  3. Set the python path in the registry to the root of the virtual environment
    PS C:\scratch> set-itemproperty -path HKLM:\SOFTWARE\Python\PythonCore\2.7\InstallPath\ -name '(Default)' -value 'C:\scatch\testenv\'
  4. Copy the contents of the Scripts folder to the root of the virtual environment
    PS C:\scratch> copy .\testenv\Scripts\* .\testenv
  5. Install PyWin32
  6. Delete the files copied to the root of the virtual environment earlier (if this isn’t a new virtual environment, you can break things, so make sure you know what was here before.)
  7. Move the .dlls it dumped in the system32 folder to the root of the virtual environment
    move C:\windows\system32\py*27.dll .\testenv -Exclude python27.dll
  8. Put the registry back the way you found it.
    PS C:\scratch> set-itemproperty -path HKLM:\SOFTWARE\Python\PythonCore\2.7\InstallPath\ -name '(Default)' -value $oldLocation

This works well enough to run django-mssql without having PyWin32 installed outside the virtual environment.  Wouldn’t it be nice if the installer just let you specify a virtual environment instead?

Leave a comment