我可以将Python Windows包安装到虚拟环境中吗?

124 投票
7 回答
33122 浏览
提问于 2025-04-16 01:26

Virtualenv 是个很棒的工具,它可以让我保持多个独立的 Python 安装,这样不同项目的依赖就不会混在一起了。

但是,如果我想在 Windows 上安装一个打包成 .exe 安装程序的包,我该怎么让它安装到虚拟环境里呢?比如,我有一个叫 pycuda-0.94rc.win32-py2.6.exe 的文件。当我运行它时,它会查看注册表,只找到一个 Python26 的安装位置,就是我虚拟环境所基于的那个公共版本。

我该怎么让它安装到虚拟环境里呢?

7 个回答

71

我知道这个问题已经很老了,而且在我接下来要讲的工具出现之前就存在了,但为了让大家在谷歌上能找到,我觉得提一下是个好主意。easy_install在Python打包工具中就像个黑羊,没人愿意承认自己在用它,因为现在有了更流行的pip。还有,虽然通过一些注册表的技巧可以解决非标准的EXE安装程序(就是有人自己做的安装程序,而不是用distutils工具做的,并且在注册表中查找安装路径),但现在有了一种更好的方法(c)来处理标准的EXE安装程序。

pip install wheel
wheel convert INSTALLER.EXE
pip install NEW_FILE_CREATED_IN_LAST_STEP.whl

最近推出的wheel格式是egg格式的替代品,起到类似的作用。这个格式也得到了pip的支持(pip是你在虚拟环境中已经安装的工具)。

如果因为某种原因pip install WHEELFILE不管用,可以试试wheel install WHEELFILE

201

是的,你可以这样做。你只需要

easy_install binary_installer_built_with_distutils.exe

惊讶吗?看起来用distutils制作的Windows二进制安装程序把.exe和.zip合成了一个.exe文件。你可以把扩展名改成.zip,看看它其实是一个有效的zip文件。我是在阅读我提问的答案时发现这个的,那个问题是 我可以在哪里下载适用于Windows的psycopg2二进制包?

更新

正如Tritium21在他的回答中提到的,现在你应该使用pip而不是easy_install。虽然pip不能安装由distutils创建的二进制包,但它可以安装新的wheel格式的二进制包。你可以使用wheel这个包将旧格式转换为新格式,但你需要先安装它。

41

我最终改编了一个脚本(http://effbot.org/zone/python-register.htm),用来在注册表中注册一个Python安装。这样我可以选择要注册的Python版本,让它成为注册表中的“主”Python,然后再运行Windows安装程序,最后再把注册表恢复到之前的状态。

# -*- encoding: utf-8 -*-
#
# script to register Python 2.0 or later for use with win32all
# and other extensions that require Python registry settings
#
# Adapted by Ned Batchelder from a script
# written by Joakim Löw for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_LOCAL_MACHINE, regpath)
    except EnvironmentError:
        try:
            reg = CreateKey(HKEY_LOCAL_MACHINE, regpath)
        except Exception, e:
            print "*** Unable to register: %s" % e
            return

    SetValue(reg, installkey, REG_SZ, installpath)
    SetValue(reg, pythonkey, REG_SZ, pythonpath)
    CloseKey(reg)
    print "--- Python %s at %s is now registered!" % (version, installpath)

if __name__ == "__main__":
    RegisterPy()

运行这个脚本时,记得用你想要注册的Python版本,它就会被添加到注册表中。需要注意的是,在Windows 7和Vista系统上,你需要有管理员权限才能执行这个操作。

撰写回答