
在 Sublime Text 中创建自定义 Build System 可以让你快速编译和运行各种语言的代码,比如 Python、C++、Go 或你自己指定的脚本。下面教你如何一步步创建并使用自己的编译运行配置。
打开 Build System 配置界面
点击菜单栏的 Tools → Build System → New Build System…,Sublime 会新建一个 JSON 格式的配置文件模板。
编写自定义 build system 配置
将默认内容替换为你的编译或运行命令。以下是一个通用结构:
{ "cmd": ["your_command", "$file"], "selector": "source.yourlang", "file_regex": "^(...*?):([0-9]+):([0-9]+):? (.*)$", "working_dir": "$file_path", "shell": true }说明各字段含义:
-
cmd:执行的命令,支持变量如
$file(当前文件)、$file_name、$file_path -
selector:关联语法类型,例如
source.python、source.cpp - working_dir:工作目录,设为文件所在目录便于相对路径操作
- shell:是否通过 shell 执行,Windows 下常设为 true 以识别 bat/sh 命令
- file_regex:解析错误输出中的文件、行、列信息(可选)
示例:Python 脚本运行
{ "cmd": ["python", "$file"], "selector": "source.python", "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]+)", "working_dir": "$file_path", "shell": true }保存为 Python_Run.sublime-build,之后在 Python 文件中按 Ctrl+B 就能运行当前脚本。
示例:C++ 编译并运行
{ "cmd": ["g++", "$file", "-o", "$file_base_name", "&&", "./$file_base_name"], "selector": "source.c++", "shell": true, "working_dir": "$file_path" }这个配置先用 g++ 编译,再运行生成的可执行文件。注意 && 是连接多条命令的关键。
保存与切换 Build System
保存后,配置文件会自动存放在 Preferences → Browse Packages → User 目录下。你可以在底部状态栏点击当前 Build System 名称,选择你刚创建的那个,或者通过 Tools → Build System 切换。
如果想快速运行不同脚本,可以为每种用途建独立的 .sublime-build 文件,比如 Run_Python、Compile_Cpp 等。
基本上就这些。写好命令、保存配置、选对语法类型,就能一键编译运行了。关键是根据系统环境调整命令(Windows 用 cmd 兼容语法,macOS/Linux 多用 bash),别忘了开启 shell 和设置工作目录。










