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

能否在远程服务器上运行本地Jupyter Notebook中的部分代码单元?

在本地Jupyter Notebook中远程运行单个代码单元的方案

针对你的需求(本地完成大部分工作,仅将个别计算密集型代码单元放到性能更强的远程Ubuntu服务器运行,且服务器存储空间有限),以下是几个高效的解决方案:

方案1:使用Jupyter单元格魔法命令%%ssh

无需编写复杂连接逻辑,直接在Notebook单元格中执行远程代码。

  1. 本地Jupyter环境安装依赖:
pip install ipython-ssh
  1. 在Notebook新建单元格,用%%ssh指定远程服务器,随后编写执行代码:
%%ssh your-username@remote-server-ip
# 切换到服务器临时目录(避免占用配额空间)
cd /tmp
# 执行计算代码,结果直接输出到本地Notebook
python -c "
import numpy as np
# 替换为你的代码单元内容
large_matrix = np.random.rand(10000, 10000)
mean_value = large_matrix.mean()
print('计算结果:', mean_value)
"

若需将结果保存到本地,可结合scp:

%%ssh your-username@remote-server-ip
cd /tmp
python -c "
import numpy as np
mean_value = np.random.rand(10000,10000).mean()
with open('/tmp/remote_result.txt', 'w') as f:
    f.write(str(mean_value))
" && scp your-username@remote-server-ip:/tmp/remote_result.txt ./local_result.txt

之后在本地读取local_result.txt即可获取结果。

方案2:使用paramiko库灵活控制远程执行

适合需要传递本地变量、获取结构化结果的场景,全程用Python代码控制流程。

  1. 本地安装依赖:
pip install paramiko
  1. 编写代码单元实现远程连接、执行与结果获取:
import paramiko

# 建立SSH连接(推荐密钥认证,避免重复输密码)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 密钥认证:替换为你的私钥路径
ssh.connect('remote-server-ip', username='your-username', key_filename='/home/your-user/.ssh/id_rsa')

# 定义远程执行代码,可直接嵌入本地变量
local_input = [10, 20, 30]
remote_code = f"""
import numpy as np
# 使用本地传递的变量
input_data = {local_input}
processed_data = np.array(input_data) * 2
print('处理结果:', processed_data.tolist())
"""

# 执行远程代码
stdin, stdout, stderr = ssh.exec_command(f'python -c "{remote_code.replace('"', '\\"')}"')

# 获取输出与错误信息
output = stdout.read().decode().strip()
error = stderr.read().decode().strip()

print('远程执行输出:', output)
if error:
    print('执行错误:', error)

# 关闭连接
ssh.close()

方案3:用sshfs挂载远程临时目录

适合运行多段代码或依赖文件的场景,将服务器临时目录挂载到本地直接操作。

  1. 本地安装sshfs:
sudo apt install sshfs
  1. 创建挂载点并挂载远程临时目录:
mkdir ~/remote-temp
sshfs your-username@remote-server-ip:/tmp ~/remote-temp
  1. 在Notebook中保存代码到挂载目录,远程执行并读取结果:
# 保存代码到远程临时目录
code_content = """
import numpy as np
result = np.random.rand(10000,10000).mean()
with open('calc_result.txt', 'w') as f:
    f.write(str(result))
"""
with open('/home/your-user/remote-temp/run_calc.py', 'w') as f:
    f.write(code_content)

# 远程运行脚本
import subprocess
subprocess.run(['ssh', 'your-username@remote-server-ip', 'cd /tmp && python run_calc.py'])

# 读取远程计算结果
with open('/home/your-user/remote-temp/calc_result.txt', 'r') as f:
    result = f.read()
print('计算结果:', result)
  1. 使用完毕后卸载挂载:
fusermount -u ~/remote-temp

优化建议

  • 优先使用SSH密钥认证:生成密钥对ssh-keygen,通过ssh-copy-id your-username@remote-server-ip将公钥传到服务器,避免重复输入密码,提升效率。
  • 精简远程代码:仅将计算密集型部分放到远程,本地完成数据预处理和结果分析,减少数据传输量。
  • 及时清理远程临时文件:在远程代码末尾添加清理逻辑(如import os; os.remove('/tmp/remote_result.txt')),避免占用服务器空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:05:35