
# Python脚本后台运行：在VPS上7×24小时不间断运行

**想让Python脚本后台运行并7×24小时不停，最可靠的做法是在VPS上为它创建虚拟环境，再用带`Restart=always`的systemd服务包装起来。** systemd会在开机时启动脚本，崩溃后自动重启，关闭SSH后脚本继续运行，输出统一写入`journalctl`。快速实验用`nohup`或tmux就够了，定时任务则可以用systemd定时器。示例基于Ubuntu 24.04和Python 3.12。


给AI智能体的提示词：


```text
在0x.cloud上创建一台s1-1服务器，系统为Ubuntu 24.04，按小时计费。先用dry_run告诉我价格，等我回复“确认”后再继续。从<仓库地址>复制我的脚本，创建虚拟环境，安装requirements.txt，并配置带Restart=always和PYTHONUNBUFFERED=1的systemd服务。确认服务器重启后脚本仍在运行，并告诉我如何查看日志。
```


## Python脚本后台运行的几种方式

| 方式 | 退出SSH后继续运行 | 崩溃后重启 | 开机自启 | 适用场景 |
|---|---|---|---|---|
| `python3 script.py` | 否 | 否 | 否 | 调试 |
| `nohup … &` | 是 | 否 | 否 | 一次性长任务 |
| tmux / screen | 是 | 否 | 否 | 交互式工作 |
| cron `@reboot` | 是 | 否 | 是 | 简单的开机启动 |
| **systemd** | 是 | 是 | 是 | **7×24小时运行的脚本** |

## 运行要求与服务器配置

- Ubuntu 24.04 LTS，已预装Python 3.12；
- 使用sudo用户而不是root（示例中为`deploy`）；
- 机器人、爬虫或监控脚本用s1-1（1 vCPU、1GB内存、15GB NVMe）即可，$4.49/月；数据处理类脚本用s1-2（2GB内存），$7.99/月。参阅[Python VPS主机](https://0x.cloud/zh/python-vps)。

为什么选s1-1：下面的示例脚本只是一个Python进程，几乎所有时间都在`time.sleep`中，内存占用只有几十MB。1GB足以容纳操作系统和这个脚本，还有富余。如果脚本要把pandas表格、图片或大型JSON文件加载到内存中，请选s1-2，否则OOM killer会杀掉它（日志中会出现`Out of memory: Killed process`）。要查看脚本的实际占用，执行`systemctl status monitor`并查看`Memory:`一行。

可以先从按小时计费开始：s1-1为$0.030750/小时（$4.49÷730×5，每个自然月最高$4.49），免开通费。


[Deploy to 0x.cloud](https://0x.cloud/cabinet/create?plan=s1-1&app=python-script)


## 准备服务器

在控制台中打开服务器的网页终端（智能体用`run_command`执行同样的命令）并安装软件包：

```bash
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-venv git
sudo ufw allow OpenSSH && sudo ufw enable
sudo ufw status
```

`python3-venv`用于创建虚拟环境。如果脚本不接受外部连接，只需开放SSH端口。

## 准备脚本和虚拟环境

```bash
mkdir ~/monitor && cd ~/monitor
python3 -m venv .venv
.venv/bin/pip install -U pip
# if you have dependencies:
.venv/bin/pip install -r requirements.txt
```

Ubuntu 24.04禁止用pip向系统Python安装包（报错`externally-managed-environment`），所以每个脚本都使用独立的环境。下面是一个每分钟检查一次网站的示例`monitor.py`：

```python
import logging
import time
import urllib.request

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
URL = "https://example.com"

while True:
    try:
        with urllib.request.urlopen(URL, timeout=10) as r:
            logging.info("status %s", r.status)
    except Exception as e:
        logging.error("failed: %s", e)
    time.sleep(60)
```

循环内的`try/except`保证一次网络错误不会让整个脚本退出。用`.venv/bin/python monitor.py`测试一下，一秒内应看到类似`2026-11-20 10:00:00,123 status 200`的一行，然后按Ctrl+C结束。

## 用systemd让Python脚本后台运行7×24小时

```bash
sudo nano /etc/systemd/system/monitor.service
```

```ini
[Unit]
Description=Python monitor script
After=network-online.target
Wants=network-online.target

[Service]
User=deploy
WorkingDirectory=/home/deploy/monitor
ExecStart=/home/deploy/monitor/.venv/bin/python monitor.py
Environment=PYTHONUNBUFFERED=1
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
```

- `ExecStart`指向虚拟环境中的Python，这样脚本才能找到依赖；
- `PYTHONUNBUFFERED=1`关闭输出缓冲，否则日志会延迟出现甚至不出现；
- `Restart=always`在脚本退出时自动重启，`RestartSec=5`设置5秒的间隔。

密钥等敏感信息放在权限为600的单独文件中，用`EnvironmentFile=/home/deploy/monitor/.env`加载。

```bash
sudo systemctl daemon-reload
sudo systemctl enable --now monitor
systemctl status monitor
journalctl -u monitor -f
```

`enable --now`设置开机自启并立即启动服务，`journalctl -f`实时输出日志。`systemctl status`中应显示`Active: active (running)`，日志中每分钟出现一行`status 200`。最后验证：执行`sudo reboot`，重新连接后再运行`systemctl status monitor`，服务应已自动运行。所有选项的说明见[创建systemd服务教程](https://0x.cloud/zh/kb/servers/chuangjian-systemd-fuwu)。如果您的脚本是Telegram机器人，请参阅[Python Telegram Bot部署教程](https://0x.cloud/zh/deploy/telegram-bot-python)。

## 定时脚本：systemd定时器

每天跑一次的任务不需要一直运行。创建两个文件：

```ini
# /etc/systemd/system/report.service
[Unit]
Description=Daily report

[Service]
Type=oneshot
User=deploy
WorkingDirectory=/home/deploy/monitor
ExecStart=/home/deploy/monitor/.venv/bin/python report.py
```

```ini
# /etc/systemd/system/report.timer
[Unit]
Description=Run daily report at 03:00

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target
```

```bash
sudo systemctl daemon-reload
sudo systemctl enable --now report.timer
systemctl list-timers
```

`Persistent=true`会在服务器关机后补跑错过的任务。`systemctl list-timers`的列表中应出现`report.timer`，`NEXT`列显示下次运行时间。想在计划之外测试任务，执行`sudo systemctl start report.service`，再查看`journalctl -u report -n 20`。传统的crontab做法见我们的[cron指南](https://0x.cloud/zh/kb/servers/crontab-dingshi-renwu)。

## 快速方案：nohup和tmux

```bash
nohup .venv/bin/python monitor.py > monitor.log 2>&1 &
```

`nohup`忽略挂断信号，`> monitor.log 2>&1`把输出和错误写入文件，`&`让进程转入后台。用`pkill -f monitor.py`停止它。交互式工作用tmux更方便：`tmux new -s work`，运行脚本，按Ctrl+b再按d分离会话。参阅[tmux指南](https://0x.cloud/zh/kb/servers/tmux-shiyong)。这两种方式在服务器重启后都不会自动恢复。

## 更新脚本

```bash
cd ~/monitor && git pull
.venv/bin/pip install -r requirements.txt
sudo systemctl restart monitor
```

修改unit文件后，需要执行`sudo systemctl daemon-reload`。

## 备份

代码放在Git中，另外备份`.env`和脚本的数据：

```bash
tar czf ~/monitor-$(date +%F).tar.gz --exclude=monitor/.venv -C ~ monitor
```

虚拟环境很容易重建，所以排除在外。在0x.cloud上，您还可以开启服务器每日备份（套餐价格+20%）或创建$0.99/月的快照。

## 常见问题排查

| 现象 | 解决方法 |
|---|---|
| 脚本在运行，但`journalctl`为空 | 添加`Environment=PYTHONUNBUFFERED=1` |
| systemd下出现`ModuleNotFoundError` | `ExecStart`用的是系统Python，改为`.venv/bin/python` |
| `start request repeated too quickly` | 脚本启动即崩溃。查看`journalctl -u monitor -n 50`并调大`RestartSec` |
| 访问文件时`Permission denied` | `User=`指定的用户不是目录所有者：`sudo chown -R deploy: ~/monitor` |
| 脚本退出后没有重启 | 用了`Restart=on-failure`而脚本正常退出。改用`Restart=always` |
| `externally-managed-environment` | 用`.venv/bin/pip`安装 |

参考文档：[systemd.service手册](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html)。

套餐选错了，或者服务器用完了？直接删除：立即停止计费，未使用的金额退回账户余额。服务器位于波兰华沙，技术支持工作时间内平均约30分钟回复（06:00–20:00 UTC）。

## 常见问题：Python脚本后台运行

**为什么关闭SSH后Python脚本就停了？**
进程属于您的终端会话，断开连接时会收到SIGHUP信号。把脚本作为systemd服务运行，或者用nohup、tmux启动。

**nohup、tmux和systemd，哪种后台运行方式最好？**
一次性任务用nohup和tmux就够了。需要7×24小时运行时请用systemd：脚本崩溃后自动重启，服务器重启后自动启动。

**为什么print()的输出在journalctl里看不到？**
输出不是写到终端时，Python会对其进行缓冲。在服务中添加Environment=PYTHONUNBUFFERED=1，或用python -u运行。

**如何定时运行Python脚本？**
用cron或systemd定时器（timer）。定时器的日志写入journalctl，Persistent=true会在服务器恢复运行后补跑错过的任务。

**可以免费让Python脚本7×24小时运行吗？**
免费方案通常限制运行时长，或让空闲应用休眠。小型VPS是可靠的选择：0x.cloud的s1-1为$4.49/月，按小时计费让您只为短期测试的实际使用小时付费（s1-1为$0.030750/小时）。


[Deploy to 0x.cloud](https://0x.cloud/cabinet/create?plan=s1-1&app=python-script)



[创建服务器: s1-1, $4.49/月](https://0x.cloud/cabinet/create?plan=s1-1)
