
# How to run a Python script 24/7 on a VPS

**To run a Python script 24/7, give it a virtualenv on a VPS and wrap it in a systemd service with `Restart=always`.** systemd starts the script at boot, restarts it after a crash, keeps it running after you close SSH and sends its output to `journalctl`. For quick experiments, `nohup` or tmux is enough, and for scheduled jobs there are systemd timers. Examples use Ubuntu 24.04 and Python 3.12.


Prompt for your AI agent:


```text
Create an s1-1 server with Ubuntu 24.04 and hourly billing on 0x.cloud. Show the dry_run price and wait for my "yes". Copy my script from <repository URL>, create a virtualenv, install requirements.txt and set up a systemd service with Restart=always and PYTHONUNBUFFERED=1. Confirm it survives a reboot and show me how to read the logs.
```


## Ways to keep a Python script running

| Method | Survives SSH logout | Restarts on crash | Starts after reboot | Best for |
|---|---|---|---|---|
| `python3 script.py` | no | no | no | debugging |
| `nohup … &` | yes | no | no | a one-off long job |
| tmux / screen | yes | no | no | interactive work |
| cron `@reboot` | yes | no | yes | simple start at boot |
| **systemd** | yes | yes | yes | **24/7 scripts** |

## Requirements and plan

- Ubuntu 24.04 LTS with Python 3.12 preinstalled;
- a sudo user rather than root (the examples use `deploy`);
- a bot, scraper or monitor fits s1-1 (1 vCPU, 1 GB RAM, 15 GB NVMe) at $4.49/mo; data processing fits s1-2 with 2 GB RAM at $7.99/mo. See [Python VPS hosting](https://0x.cloud/python-vps-hosting).

Why s1-1: the example script below is one Python process that spends nearly all its time in `time.sleep`, using tens of MB of RAM. 1 GB covers the OS and this script with room to spare. If your script loads pandas tables, images or big JSON files into memory, take s1-2, or the OOM killer will stop it (the journal shows `Out of memory: Killed process`). To see what your script really uses, run `systemctl status monitor` and read the `Memory:` line.

You can start on hourly billing: s1-1 is $0.030750 an hour ($4.49 / 730 × 5) and never more than $4.49 in a calendar month. Setup is $0.


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


## Prepare the server

Open the web console of the server in your cabinet (an agent runs the same commands with `run_command`) and install packages:

```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` provides virtual environments. If the script doesn't accept inbound connections, SSH is the only port you need.

## Set up the script and virtualenv

```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 blocks pip installs into system Python (`externally-managed-environment`), so each script gets its own environment. A sample `monitor.py` that checks a website every minute:

```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)
```

The `try/except` inside the loop stops one network error from killing the script. Test it with `.venv/bin/python monitor.py`. Within a second you should see a line like `2026-11-20 10:00:00,123 status 200`; then press Ctrl+C.

## Run the Python script 24/7 with systemd

```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` points at the venv's Python so the script finds its dependencies;
- `PYTHONUNBUFFERED=1` disables output buffering, otherwise logs show up late or not at all;
- `Restart=always` restarts the script whenever it exits, after a 5-second pause from `RestartSec=5`.

Keep secrets in a separate file with 600 permissions and load it with `EnvironmentFile=/home/deploy/monitor/.env`.

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

`enable --now` enables autostart and starts the service, and `journalctl -f` streams the log. Look for `Active: active (running)` in `systemctl status` and a `status 200` line every minute in the journal. Final check: `sudo reboot`, reconnect and run `systemctl status monitor` again; the service should be running without you touching it. Every option is covered in [how to create a systemd service](https://0x.cloud/kb/servers/systemd-service). If your script is a Telegram bot, follow [deploy a Telegram bot in Python](https://0x.cloud/deploy/telegram-bot-python).

## Scheduled scripts: systemd timers

A daily job shouldn't run all the time. Create two files:

```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` runs a missed job after the server was off. `systemctl list-timers` should list `report.timer` with the next run time in the `NEXT` column. To test the job outside the schedule, run `sudo systemctl start report.service` and read `journalctl -u report -n 20`. The classic crontab approach is in our [cron guide](https://0x.cloud/kb/servers/cron).

## Quick options: nohup and tmux

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

`nohup` ignores the hangup signal, `> monitor.log 2>&1` sends output and errors to a file, and `&` backgrounds the process. Stop it with `pkill -f monitor.py`. For interactive work, tmux is nicer: `tmux new -s work`, run the script, detach with Ctrl+b, d. See the [tmux guide](https://0x.cloud/kb/servers/tmux). Neither method survives a reboot.

## Update the script

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

After editing a unit file, run `sudo systemctl daemon-reload`.

## Back up

Keep code in Git and back up `.env` plus the script's data:

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

The venv is excluded because it's easy to rebuild. On 0x.cloud you can also enable daily server backups (+20% of the plan price) or take $0.99/mo snapshots.

## Troubleshooting

| Symptom | Fix |
|---|---|
| `journalctl` is empty but the script runs | Add `Environment=PYTHONUNBUFFERED=1` |
| `ModuleNotFoundError` under systemd | `ExecStart` uses system Python. Point it to `.venv/bin/python` |
| `start request repeated too quickly` | The script crashes on start. Read `journalctl -u monitor -n 50` and raise `RestartSec` |
| `Permission denied` on files | The `User=` account doesn't own the folder: `sudo chown -R deploy: ~/monitor` |
| Script exited and didn't restart | You used `Restart=on-failure` and it exited cleanly. Use `Restart=always` |
| `externally-managed-environment` | Install with `.venv/bin/pip` |

Reference: [systemd.service manual](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html).

Wrong plan, or done with the server? Delete it: billing stops at once and the remainder goes back to your balance. Servers are in Warsaw, and support answers in about 30 minutes on average during business hours (06:00–20:00 UTC).

## FAQ

**Why does my script stop when I close SSH?**
The process belongs to your terminal session and gets SIGHUP when you disconnect. Run it as a systemd service, with nohup, or inside tmux.

**nohup, tmux or systemd: which is best?**
nohup and tmux are fine for one-off jobs. For 24/7 operation use systemd: it restarts the script after a crash and starts it again after a reboot.

**Why don't my print() lines show up in journalctl?**
Python buffers output when it isn't writing to a terminal. Add Environment=PYTHONUNBUFFERED=1 to the service or run python with -u.

**How do I run a script on a schedule?**
Use cron or a systemd timer. Timers log to journalctl, and Persistent=true runs a missed job once the server is back up.

**Can I run a Python script 24/7 for free?**
Free tiers usually limit runtime or sleep idle apps. A small VPS is the dependable option: on 0x.cloud, s1-1 costs $4.49/mo and hourly billing keeps short tests cheap.


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



[Create server: s1-1, $4.49/mo](https://0x.cloud/cabinet/create?plan=s1-1)
