Tips on ActivePython, PyWin32 and virtualenv

activepython blog hero

When you create a pure Python sandbox using virtualenv --no-site-packages the global site-packages directory is rightfully not included … however, this poses a challenge in accessing non-trivial packages from within the virtualenv. While packages such as PyQt4 can be reinstalled into the virtualenv using pypm -E C:\myvenv install pyqt4, that is not true for PyWin32 which is included with the ActivePython distribution itself.

C:\> virtualenv --no-site-packages C:\myenv
C:\> C:\myenv\Scripts\python.exe
>>> import win32api
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named win32api
>>>

Fortunately, there is a simple workaround to get around this problem.

C:\> copy C:\Python27\Lib\site-packages\pywin32.pth C:\myenv\Lib\site-packages\
C:\> more C:\myenv\Lib\site-packages\pywin32.pth
# .pth file for the PyWin32 extensions
win32
win32\lib
Pythonwin
C:\>

Now simply edit this file (in your text editor, eg: IDLE) to contain the absolute paths:

# .pth file for the PyWin32 extensions
C:\Python27\Lib\site-packages\win32
C:\Python27\Lib\site-packages\win32\lib
C:\Python27\Lib\site-packages\Pythonwin

That’s it — you can now import pywin32 from the newly created virtualenv and still exclude the packages in your global site-packages directory.

C:\myenv\Scripts\python.exe
>>> import win32api
>>>

All of this can be automated by using Fabric and fablib – which also copies other pywin32 packages, such as win32com.
Get started using ActivePython or visit PyPM Index!

Recent Posts

Webinar - Walking Dead Past Python EOL
Walking Dead Past Python EOL

With Red Hat dropping Python 2 support, more organizations will be stuck maintaining zombie legacy apps. Stop racing against EOL dates and letting bad practices infect your new projects. Get current and stay current with the latest open source language versions.

Read More
Scroll to Top