如何在Ubuntu Server上将Python脚本作为服务运行?
Got it, let's get your Python script running as a persistent service on Ubuntu so you don't have to keep your SSH session open. Here's a step-by-step guide tailored to your needs:
1. Upload your Python script to the server
First, get your script onto the Ubuntu server. You can use scp directly from your local terminal:
scp /path/to/your/local/script.py your-username@server-ip:/opt/my-scripts/
If the /opt/my-scripts/ directory doesn't exist on the server, log in via SSH and create it first:
mkdir -p /opt/my-scripts
Then make sure your script has the necessary permissions (at least read access for the user running it):
chmod +r /opt/my-scripts/script.py
2. Create a systemd service file
Ubuntu uses systemd for managing services, so we'll create a custom service config to run your script.
Open a new service file with sudo privileges:
sudo nano /etc/systemd/system/python-script.service
Paste the following config, adjusting the values to match your setup:
[Unit] Description=My Background Python Script # Uncomment the line below if your script needs network access # After=network.target [Service] # Replace with your server username User=your-username # Set to the directory where your script lives WorkingDirectory=/opt/my-scripts # Path to Python and your script; use your virtual env Python path if needed ExecStart=/usr/bin/python3 /opt/my-scripts/script.py # Set to "no" for one-time tasks (script runs once then exits) Restart=no # Send logs to systemd's journal (easy to view later) StandardOutput=journal+console StandardError=inherit [Install] WantedBy=multi-user.target
Save and exit nano: press Ctrl+O, hit Enter, then Ctrl+X.
3. Start and manage the service
Now let's set up the service to run independently:
- Reload systemd to detect the new service:
sudo systemctl daemon-reload - (Optional) If you want the script to run automatically on server boot:
sudo systemctl enable python-script.service - Start the service right away:
sudo systemctl start python-script.service
4. Check status and logs
You can verify if your script is running (or completed, for one-time tasks) with:
sudo systemctl status python-script.service
To view detailed logs (including any output/errors from your script):
# View all logs for the service journalctl -u python-script.service # Or track logs in real-time journalctl -u python-script.service -f
Extra tips
- If your script uses a virtual environment, replace the
ExecStartpath with your venv's Python binary (e.g.,/opt/my-scripts/venv/bin/python3). - Make sure any file paths in your script are absolute (not relative) to avoid issues with the service's working directory.
- For one-time tasks, after the script finishes, the service will show a "success" status in
systemctl status.
内容的提问来源于stack exchange,提问作者Klaus

