Search code examples
pythonvirtualenvpy2exedistutils

Cannot import distutils from within a py2exe-compiled script


I am on Windows Server 2012R2, trying to compile a script with py2exe, within a virtualenv, and I'm getting issues whenever one of the application scripts tries to "import distutils" (in my case, it's somewhere inside a 3rd-party library, but I reduced the problem here).

Steps to reproduce:

  • Create a virtualenv

    virtualenv venv
    call venv\Scripts\activate
    
  • Install py2exe inside the virtualenv

    easy_install --always-unzip py2exe-0.6.9.win64-py2.7.amd64.exe
    
  • Create setup.py

    from distutils.core import setup
        try:
            import py2exe
        except:
            pass
    
    setup(
        console=[
            'py2exe_distutils.py'
        ]
    )
    
  • Create py2exe_distutils.py

    import distutils
    
  • Run py2exe

    python setup.py py2exe
    
  • Try to run the generated executable

    dist\py2exe_distutils.exe
    

It returns:

    C:\Users\root\p\dist\library.zip\distutils\__init__.py:14: UserWarning: The virtualenv distutils package at %s appears to be in the same location as the system distutils?
    Traceback (most recent call last):
      File "py2exe_distutils.py", line 6, in <module>
        import distutils
      File "distutils\__init__.pyc", line 25, in <module>
    ImportError: cannot import name dist

The script runs fine when I run it directly (python py2exe_distutils.py), even from within the virtualenv.

Am I trying to do something unsupported by py2exe, or is something wrong with my setup?


Solution

  • I had the same problem while creating an executable that used pandas 0.12.0. This worked for me: before you create the executable, copy the distutils folder from the base python installation

    robocopy C:\Python27\Lib\distutils venv\Lib\distutils /E /COPY:DAT
    

    I am using virtualenv 12.0.4 and py2exe 0.6.6 on Windows 7 Professional. Some extra insight can be found here. This answer pointed me in the direction of just copying the files.