我尝试安装Python包dulwich:

pip install dulwich

但我收到了一条神秘的错误消息:

error: Unable to find vcvarsall.bat

如果我尝试手动安装软件包,也会发生同样的情况:

> python setup.py install
running build_ext
building 'dulwich._objects' extension
error: Unable to find vcvarsall.bat

当前回答

我花了将近2天的时间来研究如何在我的python 3.4 64位版本中解决这个问题:python 3.4.3(v3.4.3:9b73f1c3e601,2015年2月24日,22:44:40)[MSC v.1600 64位(AMD64)]

解决方案1,硬:(在阅读之前,先阅读下面的解决方案2)最后,这是帮助我的:

安装Visual C++2010学习版安装Microsoft Windows SDK v7.1 for Windows 7在C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC\bin\amd64中手动创建vcvars64.bat文件,该文件包含CALL“C:\Program Files\Microsoft SDK \Windows\v7.1\bin\SetEnv.cmd”/x64或其他路径,具体取决于安装位置(这似乎是可选的)安装Microsoft Visual Studio 2010 Service Pack 1以及针对Windows SDK 7.1的Microsoft Visual C++2010 Service Pack 2编译器更新之后,我尝试pip安装numpy,但收到以下错误:get_mathlib_info中的文件“numpy\core\setup.py”,第686行raise RuntimeError(“断开的工具链:无法链接简单的C程序”)运行时错误:工具链断裂:无法链接简单的C程序我在C:\Python34\Lib\distutils\msvc9compiler.py中将mfinfo更改为Nonehttps://stackoverflow.com/a/23099820/4383472最后,在pipinstallnumpy命令之后,我的avast防病毒软件试图干扰安装过程,但我很快禁用了它

花了很长时间——numpy编译了几分钟,我甚至认为有错误,但最终一切都正常。

解决方案2,简单:(我知道这一方法已经在一个高投票率的答案中被提及,但让我重复一遍,因为它确实更容易)在经历了所有这些工作之后,我明白了对我来说最好的方法就是使用来自http://www.lfd.uci.edu/~gohlke/pythonlibs/未来。有一个很小的机会,我将永远需要一些包(或包的版本),而这个网站不包含。这样安装过程也快得多。例如,要安装numpy:

donwload numpy‑1.9.2+mkl‑cp34‑none‑win_amd64.whl(如果您有Python 3.4 64位)在命令提示符或powershell中,使用pip pip install numpy‑1.9.2+mkl‑cp34‑none‑win_amd64.whl(或文件的完整路径,具体取决于命令提示符的打开方式)进行安装

其他回答

更新:评论指出,此处的说明可能很危险。请考虑使用Visual C++2008速成版或专门构建的Microsoft Visual C++编译器Python版(详细信息),不要使用下面的原始答案。原始错误消息表示未安装所需版本的Visual C++。


对于Windows安装:

在为包安装运行setup.py时,Python 2.7会搜索已安装的Visual Studio 2008。通过在调用setup.py之前在VS90COMNTOOLS环境变量中设置正确的路径,可以诱骗Python使用较新的Visual Studio。

根据安装的Visual Studio版本执行以下命令:

Visual Studio 2010(VS10):SET VS90COMNTOOLS=%VS100COMNTOOLS%Visual Studio 2012(VS11):SET VS90COMNTOOLS=%VS110COMNTOOLS%Visual Studio 2013(VS12):SET VS90COMNTOOLS=%VS120COMNTOOLS%Visual Studio 2015(VS14):SET VS90COMNTOOLS=%VS140COMNTOOLS%


警告:如下所述,如果您试图编译python模块,则此答案不太可能奏效。

有关详细信息,请参阅在Windows上为Python 2.7构建lxml。

@monkey给出的答案是正确的答案之一,但不完整。

如果您想使用MinGW,您应该选择C、C++以及MinGW安装过程中建议的其他开发工具,以获得“make.exe”

您还必须在env中将路径设置为make.exe。

要完成他的回答,请执行以下步骤:

将mingw32的bin目录添加到环境变量中追加C:\Programs\MinGW\bin;C: \Programs\MinGW\msys\1.0\bin;到PATH将位于C:\Python26\Lib\distutils\distutils.cfg的distutils.cfg文件编辑(如果不存在则创建)为:[生成]编译器=mingw32

确保通过打开新的cmd.exe来设置环境变量。

调用importsetuptools将对补丁distutils进行模仿,以强制与Visual Studio兼容。手动调用vcvars32.bat将设置虚拟环境并防止编译器抛出其他常见错误。对于VS 2017,文件位于

“C:\Program Files(x86)\Microsoft VisualStudio\2017\社区\VC\Auxiliary\Build\vcvars32.bat“

以下是我用来将.pyx文件快速编译为.pyd的安装脚本:(注意:它使用第三方模块发送2个

# cython_setup.py
import sys, os, time, platform, subprocess
from setuptools import setup, find_packages
from Cython.Build import cythonize
from traceback import format_exc

# USAGE:
#
#   from cython_setup import run
#   run(pyx_path)

# vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"

# NOTE: to use visual studio 2017 you must have setuptools version 34+
vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars32.bat"


def _build_ext():
    try:
        pyx_path = sys.argv.pop(-1)
        pyx_path = os.path.abspath(pyx_path)
        if not os.path.exists(pyx_path):
            raise FileNotFoundError(f"{pyx_path} does not exist")
        project_name = sys.argv.pop(-1)
        os.chdir(os.path.abspath(os.path.dirname(pyx_path)))

        print("cwd: %s" % os.getcwd())
        print(os.path.abspath("build"))
        setup(
            name=project_name,
            # cmdclass = {'build_ext': build_ext},
            packages=find_packages(),
            # ext_modules=cythonize(extensions)
            ext_modules=cythonize(pyx_path,
                                  compiler_directives={'language_level': 3, 'infer_types': True, 'binding': False},
                                  annotate=True),
            # include_dirs = [numpy.get_include()]
            build_dir=os.path.abspath("build")
        )
    except:
        input(format_exc())


def retry(func):
    def wrapper(*args, **kw):
        tries = 0
        while True:
            try:
                return func(*args, **kw)
            except Exception:
                tries += 1
                if tries > 4:
                    raise
                time.sleep(0.4)

    return wrapper


@retry
def cleanup(pyx_path):
    from send2trash import send2trash
    c_file = os.path.splitext(pyx_path)[0] + ".c"
    if os.path.exists(c_file):
        os.remove(c_file)

    if os.path.exists("build"):
        send2trash("build")


def move_pyd_files(pyx_path):
    pyx_dir = os.path.dirname(pyx_path)
    build_dir = os.path.join(pyx_dir, "build")
    if not os.path.exists(build_dir):
        raise RuntimeError(f"build_dir {build_dir} did not exist....")
    found_pyd = False
    for top, dirs, nondirs in os.walk(build_dir):
        for name in nondirs:
            if name.lower().endswith(".pyd") or name.lower().endswith(".so"):
                found_pyd = True
                old_path = os.path.join(top, name)
                new_path = os.path.join(pyx_dir, name)
                if os.path.exists(new_path):
                    print(f"removing {new_path}")
                    os.remove(new_path)
                print(f"file created at {new_path}")
                os.rename(old_path, new_path)
    if not found_pyd:
        raise RuntimeError("Never found .pyd file to move")

def run(pyx_path):
    """
    :param pyx_path:
    :type pyx_path:
    :return: this function creates the batch file, which in turn calls this module, which calls cythonize, once done
    the batch script deletes itself... I'm sure theres a less convoluted way of doing this, but it works
    :rtype:
    """
    try:
        project_name = os.path.splitext(os.path.basename(pyx_path))[0]
        run_script(project_name, os.path.abspath(pyx_path))
    except:
        input(format_exc())


def run_script(project_name, pyx_path):
    dirname = os.path.dirname(pyx_path)
    # ------------------------------
    os.chdir(dirname)
    if os.path.exists(vcvars):
        #  raise RuntimeError(
        # f"Could not find vcvars32.bat at {vcvars}\nis Visual Studio Installed?\nIs setuptools version > 34?")
        subprocess.check_call(f'call "{vcvars}"', shell=True)

    cmd = "python" if platform.system() == "Windows" else "python3"
    subprocess.check_call(f'{cmd} "{__file__}" build_ext "{project_name}" "{pyx_path}"', shell=True)
    move_pyd_files(pyx_path)
    cleanup(pyx_path)


if len(sys.argv) > 2:
    _build_ext()

以下步骤为我解决了这个问题,我正尝试使用cython扩展创建设置。

安装Microsoft Visual C++编译器Python 2.7版默认安装位置为@C: \Users\PC user\AppData\Local\Programs\Common\Microsoft\Visual C++对于Python这实际上可能会解决问题,请在继续之前测试一次。如果失败,请检查VC中的位置++对于python,vcvarsall.bat文件位于打开msvc9compiler.py记事本中distutils包的文件。在我的箱子里@C: \Anaconda2\Lib\distutils\msvc9compiler.py find_vcvarsall函数在此文件中,通过打印版本来确定VC的版本论点对于Python 2.7,可能是9.0现在创建一个环境变量VS90COMNTOOLS,指向C: \Users\PC user\AppData\Local\Programs\Common\Microsoft\Visual C++用于Python\9.0\VC\bin出于某种原因,distutils期望vcvarsall.bat文件应位于VCdir中,但对于python工具则为VC++它位于9.0的根目录中。要解决此问题,请从path.join(大致围绕第247行)#productdir=os.path.join(toolsdir,os.pardir,os.pardir,“VC”)productdir=os.path.join(toolsdir,os.pardir,os.pardir)

以上步骤为我解决了问题。

2016年解决这一问题的最简单方法是安装Chocolatey,然后安装vcpython27包。打开Powershell:

> iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
> choco install python2 -y
> choco install vcpython27 -y