You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WSL(Ubuntu)虚拟环境中如何将Python3设为默认执行版本?

如何将Python3设为WSL(Ubuntu)的默认Python版本

问题描述

我是Linux新手,使用WSL(Ubuntu)环境。在虚拟环境中运行以下Python代码时出现报错,但在线IDE中运行相同代码正常,且已在虚拟环境安装最新版Python:

测试代码

word_one = input("Enter the first word:")  # 输入mark
word_two = input("Enter the second word:") # 输入mary

# 比较输出
if word_one > word_two:
    print(word_two,word_one)
else:
    print(word_one,word_two)

执行命令

python test.py

报错信息

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    word_one = input("Enter the first word:")
  File "<string>", line 1, in <module>
NameError: name 'mark' is not defined

问题补充

即使虚拟环境安装了最新版Python,系统仍默认使用Python2执行脚本,使用python3 test.py可正常运行。想知道是否可以将Python3设为默认执行版本,让输入python test.py时自动调用最新版Python。

解决方法

方法1:系统级全局配置(update-alternatives)

这是适用于所有用户的系统级设置:

  1. 先获取Python3的安装路径:
    which python3
    
    输出示例:/usr/bin/python3.10
  2. 将Python3注册到系统替代项:
    sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.10 1
    
    (替换/usr/bin/python3.10为你的实际路径,最后的1是优先级,数值越大优先级越高)
  3. 选择默认Python版本:
    sudo update-alternatives --config python
    
    在弹出的选项列表中输入对应Python3的编号,回车确认即可。

方法2:用户级别名配置

仅对当前用户生效,无需管理员权限:

  1. 编辑shell配置文件(bash用~/.bashrc,zsh用~/.zshrc):
    nano ~/.bashrc
    
  2. 在文件末尾添加别名规则:
    alias python='python3'
    
  3. 让配置立即生效:
    source ~/.bashrc
    
    新开终端后,执行python --version即可验证默认版本已切换为Python3。

方法3:虚拟环境内默认设置

激活虚拟环境后,环境内的python命令默认指向该环境的Python3版本(虚拟环境会隔离系统Python),如果日常开发依赖虚拟环境,激活后直接用python命令即可。


内容的提问来源于stack exchange,提问作者ben_stays_anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:31:17