distutils 'module' object has no attribute '__version__'

这个问题出现在使用cx_freeze打包tensorflow应用这种情况下。

原因是python虚拟环境里的distutils模块其实是指向系统环境里的distutils模块的实现的,为了定位系统的distutils模块,使用了一个trick,import opcode模块,由opcode模块的位置找到系统库目录,因为一般opcode模块只在系统环境下有,但是,一旦遇到cx_freeze,这个trick就玩砸了,因为opcode会被定位到cx_freeze打包出的library.zip里面,那里确实有opcode.pyc,导致类似标题的错误。

我的解决办法是直接把系统库目录/usr/lib64/python2.7 写进python虚拟环境里的distutils模块里的__init__.py里面,结果类似这样:

import os
import sys
import warnings
import imp
import opcode # opcode is not a virtualenv module, so we can use it to find the stdlib
              # Important! To work on pypy, this must be a module that resides in the
              # lib-python/modified-x.y.z directory

dirname = os.path.dirname

# cause bug with cx_freeze
#distutils_path = os.path.join(os.path.dirname(opcode.__file__), 'distutils')
distutils_path = os.path.join('/usr/lib64/python2.7', 'distutils')
if os.path.normpath(distutils_path) == os.path.dirname(os.path.normpath(__file__)):
    warnings.warn(
        "The virtualenv distutils package at %s appears to be in the same location as the system distutils?")
else:
    __path__.insert(0, distutils_path)
    real_distutils = imp.load_module("_virtualenv_distutils", None, distutils_path, ('', '', imp.PKG_DIRECTORY))
    # Copy the relevant attributes
    try:
        __revision__ = real_distutils.__revision__
    except AttributeError:
        pass

    __version__ = real_distutils.__version__

from distutils import dist, sysconfig

你可能感兴趣的:(python,cx_freeze,distutils)