我尝试安装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

当前回答

调用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()

其他回答

更新:评论指出,此处的说明可能很危险。请考虑使用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。

我没有看到任何使用vswhere的答案,我认为这是自Visual Studio 15.2以来正确的方法。

下面是我运行vsvars64.bat的方法(我想这与vsvarsall类似)

def init_vsvars():
    cprint("")
    cprint_header("Initializing vs vars")
    vswhere_path = r"%ProgramFiles(x86)%/Microsoft Visual Studio/Installer/vswhere.exe"
    vswhere_path = path.expandvars(vswhere_path)
    if not path.exists(vswhere_path):
        raise EnvironmentError("vswhere.exe not found at: %s", vswhere_path)

    vs_path = common.run_process(".", vswhere_path,
                                 ["-latest", "-property", "installationPath"])
    vs_path = vs_path.rstrip()

    vsvars_path = os.path.join(vs_path, "VC/Auxiliary/Build/vcvars64.bat")
    # common.run_process(".", vsvars_path, [])
    os.system('"%s"' % vsvars_path)

run_process做了很多事情,但基本上归结为:

    output = ""
    process = subprocess.Popen(
        commandline,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True)
    for stdout_line in iter(process.stdout.readline, ""):
        cprint(stdout_line)
        output += stdout_line
    process.stdout.close()

    return_code = process.wait()
    return output

我找到了解决方案。我也遇到了同样的问题和错误,安装“amara”。我安装了mingw32,但需要配置distutils。

我已经安装了Python 2.6。我将mingw32安装到C:\programs\mingw\将mingw32的bin目录添加到环境变量:append c:\programs\MinGW\bin;到PATH将位于C:\Python26\Lib\distutils\distutils.cfg的distutils.cfg文件编辑为:[生成]编译器=mingw32现在运行easy_install.exe amara。

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

我遵守了指示http://springflex.blogspot.ru/2014/02/how-to-fix-valueerror-when-trying-to.html.但什么都没发生。然后我安装了2010 Visual Studio Express(http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express)遵循建议http://blog.python.org/2012/05/recent-windows-changes-in-python-33.html它帮助了我

我也遇到了同样的错误(我觉得这很愚蠢,而且对错误消息没有任何帮助),尽管有一个C编译器可用,我还是继续遇到问题。

令人惊讶的是,最终对我有用的只是将pip和setuptools升级到最新版本。希望这对其他人有所帮助。