code runner 运行 python 时需手动配置虚拟环境路径;java 需类名文件名一致并切换工作目录;ts/rust/go 等需自定义 executormap 命令;中文乱码应统一 utf-8 编码或启用 runinterminal。

Code Runner 运行 Python 文件报 ModuleNotFoundError
默认用系统 Python,但你项目用的是虚拟环境,Code Runner 根本不知道——它只认 python 命令在 PATH 里的位置。
- 打开 VSCode 设置(
Ctrl+,),搜code-runner.executorMap,点「在 settings.json 中编辑」 - 找到
"python"对应的命令,把"python -u"改成你的虚拟环境路径,比如:"/path/to/venv/bin/python -u"(macOS/Linux)或"C:\Users\xxx\venv\Scripts\python.exe -u"(Windows) - 改完保存,重启 VSCode 或右键「Run Code」前先确认终端里
which python或where python输出是否匹配
Java 文件运行失败:找不到 Main 类或 class not found
Code Runner 默认按文件名编译运行,但 Java 要求类名和文件名严格一致,且 public class 名必须跟文件同名;更关键的是,它不会自动 cd 到源码目录再执行 javac/java。
- 确保
.java文件里只有一个public class,且类名与文件名(不含.java)完全一致,大小写都不能错 - 在
code-runner.executorMap里重写 Java 配置,加入工作目录切换逻辑,例如:"java": "cd $dir && javac $fileName && java $fileNameWithoutExt" - 如果用了包(
package),必须把文件放在对应子目录中(如com/example/Main.java),并把cd $dir改成cd $dir/../..或直接用cd $workspaceRoot,否则java com.example.Main找不到类路径
如何让 Code Runner 一键运行 TypeScript、Rust、Go 等非默认语言
它不内置支持,但能靠自定义命令接入——关键是写对编译+执行两步,且注意路径变量和错误反馈是否可见。
- TS:用
"typescript": "cd $dir && tsc $fileName && node $fileNameWithoutExt.js",前提是已全局装了tsc;推荐加--noEmitOnError防止生成残缺 JS - Rust:用
"rust": "cd $dir && rustc $fileName && ./$fileNameWithoutExt"(Linux/macOS);Windows 要写成./$fileNameWithoutExt.exe - Go:用
"go": "cd $dir && go run $fileName"即可,不用编译,但注意go.mod是否在当前目录,否则会报no Go files in current directory
输出中文乱码(尤其 Windows 上的 Python/Java)
不是编码设置问题,是 Code Runner 启动的终端默认用系统旧编码(如 GBK),而代码文件是 UTF-8,print 出来就崩。
- Python:在 executorMap 里改成
"python -u -c "import sys; sys.stdout.reconfigure(encoding='utf-8'); exec(open('$fileName').read())""(仅 Python 3.7+) - Java:加 JVM 参数
-Dfile.encoding=UTF-8,完整命令如:cd $dir && javac $fileName && java -Dfile.encoding=UTF-8 $fileNameWithoutExt - 更省事的办法:在 VSCode 设置里打开
code-runner.runInTerminal,让它跑在你配置好的、UTF-8 的集成终端里(比如 Windows Terminal + PowerShell with UTF-8)
$dir 和 $fileNameWithoutExt 到底指哪一层目录、有没有隐藏扩展名、当前工作目录是不是你想象的那个。多打两次 echo $dir 或 pwd 看一眼,比硬猜快得多。











