在 Ubuntu 上用 Python 写“服务”,通常有几种常见方式,取决于你是想:
下面我按最常见、最推荐的方式给你讲。
例如:一个后台运行、每隔几秒打印日志的 Python 服务
my_service.pyimport time
import logging
logging.basicConfig(
filename="/var/log/my_service.log",
level=logging.INFO
)
def main():
while True:
logging.info("service is running...")
time.sleep(5)
if __name__ == "__main__":
main()
⚠️ 注意:真实服务不要
while True裸写,后面会讲更规范方式
Ubuntu 18.04+ 都用 systemd
sudo vim /etc/systemd/system/my_service.service
内容示例:
[Unit]
Description=My Python Service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/my_service/my_service.py
WorkingDirectory=/opt/my_service
User=myuser
Restart=always
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
说明:
ExecStart:Python 解释器 + 脚本绝对路径User:不要用 root(安全)Restart=always:崩溃自动重启
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable my_service
sudo systemctl start my_service
systemctl status my_service
journalctl -u my_service -f
pip install flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "hello service"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
然后同样用 systemd 启动即可。
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 myapp:app
systemd 里写:
ExecStart=/usr/local/bin/gunicorn -w 4 -b 0.0.0.0:8000 myapp:app
避免裸 while True:
import signal
import sys
def handler(signum, frame):
sys.exit(0)
signal.signal(signal.SIGTERM, handler)
或使用:
python-daemonsystemd-python| 需求 | 推荐方案 |
|---|---|
| 后台任务 | Python + systemd |
| Web 服务 | Flask / FastAPI + gunicorn |
| 定时任务 | systemd timer / cron |
| 长连接 | asyncio / websockets |
如果你愿意,可以告诉我:
我可以直接帮你写一份可用的服务模板。