在 Ubuntu VPS 上安装 uv 并优雅地离线运行代码
TL; DR: 实战推荐组合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| # 1. 安装 uv + tmux
curl -LsSf https://astral.sh/uv/install.sh | sh && source ~/.bashrc
sudo apt install -y tmux
# 2. 初始化项目
mkdir myproject && cd myproject
uv init
uv add requests torch # 添加依赖
# 3. 在 tmux 中运行
tmux new -s train
uv run main.py
# 4. Ctrl+B, D 分离 → 安心关掉 SSH
# 5. 第二天连回来 → tmux attach -t train,接着看输出
|
一、安装 uv
1
2
3
4
5
6
7
8
| # 官方推荐的一键安装方式
curl -LsSf https://astral.sh/uv/install.sh | sh
# 安装完成后加载环境变量
source ~/.bashrc
# 验证安装
uv --version
|
二、SSH 断联不中断的几种方案
方案 1:tmux(最推荐)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| # 安装 tmux
sudo apt update && sudo apt install -y tmux
# 创建一个命名会话
tmux new -s myproject
# ========= 在 tmux 会话中运行你的代码 =========
cd /path/to/project
uv run main.py
# ================================================
# 按 Ctrl+B 然后按 D —— 分离(detach)会话,回到终端
# 此时即使 SSH 断开,代码仍在后台运行
# 重新连上 SSH 后,重新接入会话:
tmux attach -t myproject
# 其他常用命令:
tmux ls # 列出所有会话
tmux kill-session -t myproject # 杀掉会话
|
tmux 速查:
Ctrl+B, D → 分离会话(代码继续跑)
Ctrl+B, [ → 进入滚动/复制模式(用方向键翻看历史输出)
Ctrl+B, % → 左右分屏
Ctrl+B, " → 上下分屏
q → 退出滚动模式
方案 2:screen
1
2
3
4
5
6
7
8
9
10
11
12
| sudo apt install -y screen
# 创建会话
screen -S myproject
# 运行代码
uv run main.py
# Ctrl+A 然后按 D —— 分离
# 重新接入
screen -r myproject
|
方案 3:nohup(适合一次性后台任务)
1
2
3
4
5
6
7
8
9
10
11
| cd /path/to/project
# 用 uv 的虚拟环境直接运行
nohup uv run main.py > output.log 2>&1 &
# 查看运行状态
jobs -l # 当前 shell 内查看
ps aux | grep main.py # 另开 shell 查看
# 查看输出
tail -f output.log
|
缺点:无法交互,只能看日志,适合不需要输入的批量任务。
方案 4:systemd 服务(适合长期运行的服务)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| sudo tee /etc/systemd/system/myapp.service << 'EOF'
[Unit]
Description=My Python App
After=network.target
[Service]
Type=simple
User=your_username
WorkingDirectory=/path/to/project
ExecStart=/home/your_username/.local/bin/uv run main.py
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
EOF
# 启用并启动
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
# 常用命令
sudo systemctl status myapp # 查看状态
sudo journalctl -u myapp -f # 实时查看日志
sudo systemctl restart myapp # 重启
sudo systemctl stop myapp # 停止
|
三、方案对比
| 方案 | 交互式 | 断线恢复 | 自动重启 | 适用场景 |
|---|
| tmux | ✅ | ✅ | ❌ | 调试、开发、需要看实时输出 |
| nohup | ❌ | ❌ | ❌ | 一次性脚本、批量训练 |
| systemd | ❌ | ✅ | ✅ | 长期运行的服务、API 服务器 |
总结:日常开发调试用 tmux,生产环境用 systemd,两者组合就能覆盖绝大多数场景。