Sublime Text 运行 Python 依赖系统已安装的 Python 环境及正确路径配置,需先验证命令行中 python 或 python3 是否可用,再通过自定义 Build System(如 Python.sublime-build)调用对应命令,并注意 shell 环境变量加载差异与平台适配。

Sublime Text 本身不带 Python 运行环境,所谓“直接运行”,本质是配置一个 Build System,让 Sublime 调用系统已安装的 python 命令执行当前文件。关键不是 Sublime 多厉害,而是你本地有没有可用的 python,以及路径对不对。
确认 python 是否在命令行可用
这是最容易被跳过的一步。很多人配完 Build System 却提示 command not found: python 或 'python' is not recognized,根本原因就是 Sublime 启动的 shell 没加载你的环境变量(尤其是 Windows 的 PATH 或 macOS/Linux 的 shell profile)。
- 打开终端(macOS/Linux)或命令提示符/PowerShell(Windows),输入
python --version或python3 --version,必须有输出 - 如果只有
python3可用(常见于较新 macOS 或 Linux),就别硬写python;如果 Windows 上装的是 Python 3.12,默认可能注册为py,试试py -3 --version - Sublime 在 macOS/Linux 下默认用
/bin/sh,不会读~/.zshrc;Windows 下默认用cmd.exe,不一定继承 PowerShell 的 PATH
创建自定义 Build System(推荐 JSON 方式)
不要改默认的 Python Build System(它只支持 python 命令且无错误高亮),新建一个更可控的。路径:Tools → Build System → New Build System…
粘贴以下内容(根据你实际的 Python 命令名调整 cmd 字段):
立即学习“Python免费学习笔记(深入)”;
{
"shell_cmd": "python -u \"$file\"",
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"encoding": "utf-8",
"variants":
[
{
"name": "Run in Terminal",
"shell_cmd": "open -a Terminal.app 'file://$file_path/' && python -u \"$file\""
}
]
}
-
"shell_cmd"中的-u强制未缓冲输出,避免 print 不实时刷新 -
"file_regex"让错误行可点击跳转,正则必须严格匹配 Python 报错格式 - macOS 上想弹出终端独立运行?用
variants加个选项;Windows 对应是start cmd /c python -u "$file" & pause - 保存时务必命名为
Python.sublime-build(后缀固定),放在默认目录即可
Windows 下 py launcher 的特殊处理
如果你用的是官方 Python 安装包(非 Anaconda/Miniconda),Windows 默认注册了 py 启动器,它比硬写 python 更可靠——能自动选版本、处理 shebang、兼容不同安装路径。
这时 Build System 应该这样写 cmd:
"shell_cmd": "py -3 -u \"$file\"",
-
py -3明确调用最新 Python 3.x;py -3.12可指定小版本 - 比直接写
python少一堆 PATH 冲突问题,尤其当你装了多个 Python 版本时 - 注意:这要求你没禁用 Windows 的 Python Launcher(默认开启)
运行时看不到输出?检查这些地方
Build 成功但控制台空空如也,不是代码问题,大概率是 Sublime 的构建输出机制被卡住了。
- 确保文件已保存(
$file是文件路径,未保存的临时文件会报错) - 检查是否误选了其他 Build System(右下角状态栏看是否显示 “Python”)
- Mac 上用了
open -a Terminal.app却没反应?那是脚本执行太快,终端闪退;加&& read或换用osascript方案 - Linux 下如果用的是 Wayland,
gnome-terminal可能启动失败,改用exo-open --launch TerminalEmulator或直接放弃终端弹窗,老实用 Sublime 自带输出面板
最稳的方式永远是:先保证 shell_cmd 在终端里能跑通,再挪进 Sublime;路径、引号、转义、权限,每一步都得对得上。









