我设法在我的 Windows 上安装了最新版本。但这种方法可能会导致安全问题。 在你尝试这个之前,请注意你在做什么。
我只在 Windows 上的 Python 3.5.2 上对其进行了测试。如果您使用的是 Python2.x,最好不要尝试。
首先,弄清楚您的venv 使用的是什么版本。使用:
>>> import inspect
>>> import venv
>>> print(inspect.getsource(venv))
[the source of venv goes here]
你会发现在函数_setup_pip的定义中:
def _setup_pip(self, context):
"""Installs or upgrades pip in a virtual environment"""
# We run ensurepip in isolated mode to avoid side effects from
# environment vars, the current directory and anything else
# intended for the global Python environment
cmd = [context.env_exe, '-Im', 'ensurepip', '--upgrade',
'--default-pip']
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
这个函数告诉我们 pip 是由另一个名为 ensurepip 的 python 包安装的。所以我们将使用:
>>> import ensurepip
>>> print(inspect.getsource(ensurepip))
[the source of ensure pip goes here]
在源代码的前几行,你会得到:
_SETUPTOOLS_VERSION = "20.10.1"
_PIP_VERSION = "8.1.1"
这是ensurepip 捆绑的版本信息。但是只更改这两行只会导致失败,因为您没有更改本地 .whl 包。那么 .whl 包在哪里呢?在这里,在函数bootstrap的源代码中:
def bootstrap(*, root=None, upgrade=False, user=False,
altinstall=False, default_pip=False,
verbosity=0):
...
with tempfile.TemporaryDirectory() as tmpdir:
# Put our bundled wheels into a temporary directory and construct the
# additional paths that need added to sys.path
additional_paths = []
for project, version in _PROJECTS: # *pay attention to these lines*
wheel_name = "{}-{}-py2.py3-none-any.whl".format(project, version)
whl = pkgutil.get_data(
"ensurepip",
"_bundled/{}".format(wheel_name),
)
with open(os.path.join(tmpdir, wheel_name), "wb") as fp:
fp.write(whl)
additional_paths.append(os.path.join(tmpdir, wheel_name))
...
注意我评论的那一行。所以这告诉我们,位于ensure/_bundled/ 目录下的.whl 文件,你也可以使用inspect.getsourcefile(ensurepip)。我得到的是'c:\\python35\\lib\\ensurepip\\__init__.py'。
进入这个目录,你有两个文件:pip-8.1.1-py2.py3-none-any.whl,setuptools-20.10.1-py2.py3-none-any.whl。
我上面写的只是为了让您了解我们在做什么,所以以下是您需要做的事情:
- 转到
/your/python/lib/dir/ensurepip/_bundled/。
-
用命令下载pip wheel文件,我得到pip-9.0.1-py2.py3-none-any.whl:
$ pip download pip
-
编辑ensurepip 的来源。在ensurepip/__init__.py中,这样编辑并保存:
# _PIP_VERSION = "8.1.1" # comment this line
_PIP_VERSION = "9.0.1" # add this line
-
现在你成功了。检查 pip 版本:
$ python -m venv testpip
$ cd testpip
$ .\Scripts\activate.bat (in Linux, use '$ source ./bin/activate' instead.)
(testpip) $ pip --version
pip 9.0.1 from the \your\venv\testpip\lib\site-packages (python 3.5)
注意不要对 setuptools 做同样的事情,因为它有一些其他的依赖关系,这使得它更加复杂。
黑客愉快:)