如何使用`venv`(在Python 3.3+中)更新Python虚拟环境以使用更新的Python版本?

22

我最近安装了Python 3.8.0,与Python 3.7.4共存。

我有一些虚拟环境(使用python -m venv <directory>创建)基于v3.7.4。如何更新它们以使用v3.8.0?

我需要创建新的虚拟环境并重新安装依赖项、脚本等吗?


注意:有一些现有的问题和答案(例如这个),涉及较旧的virtualenv包/工具。我特别询问新的内置venv模块,它是自Python v3.3以来的标准内置模块,并且与virtualenv有一些不同之处。


可能是如何更改已存在的virtualenv的Python版本?的重复问题。 - gstukelj
3
可能是 Can existing virtualenv be upgraded gracefully? 的重复问题。 - jeremycg
需要吗?也许不需要。应该吗?是的。 - chepner
@gst,@jeremycg - 这些答案涉及旧的 virtualenv 模块/包。我只对现在内置的新 venv 感兴趣,其用法不同。更新以明确说明。 - LightCC
@chepner,你是否需要这样做取决于其他项目需求,不能一概而论地回答。 - LightCC
2个回答

15

我猜你在寻找的是--upgrade参数。

python -m venv --help
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT]
            ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

positional arguments:
  ENV_DIR               A directory to create the environment in.

optional arguments:
  -h, --help            show this help message and exit
  --system-site-packages
                        Give the virtual environment access to the system
                        site-packages dir.
  --symlinks            Try to use symlinks rather than copies, when symlinks
                        are not the default for the platform.
  --copies              Try to use copies rather than symlinks, even when
                        symlinks are the default for the platform.
  --clear               Delete the contents of the environment directory if it
                        already exists, before environment creation.
  --upgrade             Upgrade the environment directory to use this version
                        of Python, assuming Python has been upgraded in-place.
  --without-pip         Skips installing or upgrading pip in the virtual
                        environment (pip is bootstrapped by default)
  --prompt PROMPT       Provides an alternative prompt prefix for this
                        environment.

您需要使用目标 Python 版本运行它,例如在这种情况下:

python3.8 -m venv --upgrade <path_to_dir>

假设python3.8是您的Python 3.8.0可执行文件的名称。


这看起来是正确的 - 但用法是什么?我该如何指定要更新到哪个版本(例如)? - LightCC
python3.8 -m venv ... Python3.8 -m venv ... - RMPR
听起来不错。但是我遇到了一些问题:F:\MyCodes\python\dtprjops>python -m venv --upgrade venv 错误:[Errno 13] 权限被拒绝:'F:\MyCodes\python\dtprjops\venv\Scripts\python.exe' - Allis Gao
4
我看不出--upgrade有什么用处,因为它并不会“转移”旧的site-packages到新的Python版本的site-package目录中。因此,你仍然需要重新安装所有依赖...那这有什么意义呢? - maxschlepzig
1
对于我来说,“使用目标Python版本运行它”解决了这个问题。 - Parzival
显示剩余7条评论

3

在你的虚拟环境之外的命令提示符中运行,当VScode未运行时。

python -m venv --upgrade --upgrade-deps "c:/your/project/folder/.venv"

一些软件包没有成功升级,因此需要使用pip卸载并重新安装以解决问题。

pip uninstall pyodbc
pip install pyodbc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接