VS Code远程开发:如何设置环境变量并让Jupyter Notebook识别
解决VS Code远程开发中Jupyter Notebook继承GPU环境变量的问题
问题根源:VS Code远程终端中临时设置的环境变量不会传递给通过code命令启动的Notebook进程——远程服务器上的VS Code主进程独立于终端环境启动,Jupyter内核自然无法继承这些变量。以下是几种适配需求的解决方案:
方案1:自定义Jupyter内核自动绑定闲置GPU
让Jupyter内核启动时自动检测闲置GPU并设置环境变量,无需手动操作:
- 查看当前Jupyter内核路径:
jupyter kernelspec list - 复制默认Python内核作为自定义内核(以默认
python3内核为例):cp -r ~/.local/share/jupyter/kernels/python3 ~/.local/share/jupyter/kernels/python3-cuda-auto - 编辑自定义内核的
kernel.json文件:nano ~/.local/share/jupyter/kernels/python3-cuda-auto/kernel.json - 将文件中的
argv字段替换为以下内容(自动检测利用率低于10%的首个闲置GPU):[ "/bin/bash", "-c", "export CUDA_VISIBLE_DEVICES=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits | awk '{if ($1 < 10) print NR-1}' | head -n1); python -m ipykernel_launcher -f {connection_file}" ] - 保存文件后,在VS Code打开Notebook时,选择
python3-cuda-auto内核即可自动绑定闲置GPU。
方案2:远程SSH连接时自动设置环境变量
通过修改SSH配置,让每次连接远程服务器时自动检测闲置GPU并设置环境变量,VS Code的所有进程(包括Jupyter内核)都会继承该变量:
- 编辑本地机器的SSH配置文件:
nano ~/.ssh/config - 添加或修改服务器的配置项(替换为你的服务器信息):
Host gpu-server HostName 服务器IP地址 User 你的用户名 RemoteCommand bash -c 'export CUDA_VISIBLE_DEVICES=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits | awk '{if ($1 < 10) print NR-1}' | head -n1); exec "$SHELL"' RequestTTY yes - 保存后,通过VS Code远程连接该服务器,此时
CUDA_VISIBLE_DEVICES已自动设置,打开任意Notebook都会生效。
方案3:自定义Jupyter启动脚本
让VS Code调用自定义脚本启动Jupyter服务器,脚本中自动处理GPU环境变量:
- 在远程服务器上创建启动脚本
~/start-jupyter.sh:nano ~/start-jupyter.sh - 写入以下内容:
#!/bin/bash # 检测闲置GPU索引(利用率低于10%的首个GPU) IDLE_GPU=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits | awk '{if ($1 < 10) print NR-1}' | head -n1) export CUDA_VISIBLE_DEVICES=$IDLE_GPU # 启动Jupyter服务器 jupyter notebook "$@" - 给脚本添加执行权限:
chmod +x ~/start-jupyter.sh - 在VS Code的远程设置中,搜索
jupyter.executable,将其值设置为~/start-jupyter.sh。此后VS Code启动Jupyter时会自动设置GPU环境变量。
内容的提问来源于stack exchange,提问作者user23338870
相关产品推荐
相关产品推荐

