安装和管理最新的Python3环境(以Mac为例)

背景:

随着大模型技术的快速发展,各种基于AI的测试技术也层出不穷,有些场景需要在较高版本的Python3环境下实现,否则可能会出现兼容性问题。另外考虑自己对于Python3的各个版本环境的管理和使用其实一直都不是特别的清楚,主打一个"能用"就行。

因此,趁着这个机会梳理下一些最基本的Python3环境管理,以Mac系统为例。(2025.3.23)

准备工作:

  • 查看当前系统已有的Python3版本,为3.9.6
bash 复制代码
~ % python3    
Python 3.9.6 (default, May  7 2023, 23:32:44) 
[Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
  • 可以使用Homebrew管理Python,如果尚未安装 Homebrew,可以在终端中输入以下命令进行安装:
bash 复制代码
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  • 更新Homebrew,确保Homebrew是最新版本,以避免潜在的安装问题。
bash 复制代码
brew update

安装最新的Python3:

bash 复制代码
brew install python

预期执行安装命令后正常情况下的输出如下类似,最后也会打印出对应的安装位置,比如我的是:/opt/homebrew/bin/python3(对应的pip3位置在:/opt/homebrew/bin/pip3)

bash 复制代码
==> [email protected]
Python is installed as
  /opt/homebrew/bin/python3

Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, are installed into
  /opt/homebrew/opt/[email protected]/libexec/bin

验证最新版本的Python3:

符合预期情况:

重新打开一个终端窗口,查看最新的python3版本,预期已经是我们安装最新的Python3环境了。

不符合预期情况

如果默认Python3不是刚安装的最新的,可以通过修改 Shell 配置文件实现。适用于 zsh (默认 Shell)或 bash

(1)确定当前 Shell

bash 复制代码
echo $SHELL
  • 如果是 zsh,配置文件是 ~/.zshrc

  • 如果是 bash,配置文件是 ~/.bashrc~/.bash_profile

(2)修改 PATH 并创建别名 在 ~/.zshrc~/.bashrc 里添加:(以上述你自己安装的目录为准)

bash 复制代码
export PATH="/opt/homebrew/opt/[email protected]/libexec/bin:$PATH"
alias python="/opt/homebrew/bin/python3"
alias pip="/opt/homebrew/bin/pip3"

(3)应用修改生效

bash 复制代码
source ~/.zshrc  # 如果使用 bash,则运行 source ~/.bashrc

如果你的Python版本可能需要频繁切换,推荐使用 pyenv 管理,具体可以自行学习。

相关推荐
m0_6759882313 天前
Leetcode3110:字符串的分数
算法·leetcode·字符串·python3
m0_6759882320 天前
Leetcode2597:美丽子集的数目
算法·leetcode·回溯·python3
m0_6759882322 天前
Leetcode2848:与车相交的点
算法·leetcode·python3
m0_675988231 个月前
Leetcode350:两个数组的交集 II
算法·leetcode·数组·哈希表·python3
m0_675988231 个月前
Leetcode1206:设计跳表
算法·leetcode·跳表·python3
m0_675988231 个月前
Leetcode2080:区间内查询数字的频率
数据结构·算法·leetcode·python3
m0_675988231 个月前
Leetcode1760:袋子里最少数目的球
数据结构·算法·leetcode·二分查找·python3
m0_675988232 个月前
Leetcode1728:猫和老鼠 II
linux·运维·数据库·算法·leetcode·python3
m0_675988232 个月前
Leetcode45:跳跃游戏 II
算法·leetcode·动态规划·贪心·python3