You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将自定义Python HTTP服务器以Systemd服务方式正常运行

问题原因

你的systemd服务配置里Type=notify,但自定义Python脚本没有向systemd发送就绪通知,导致systemd一直等待服务发出"启动完成"的信号,所以执行systemctl start python时终端卡住,尽管服务实际已经在运行。

修复方案

有两种可行的修复方式,选其一即可:

方案一:修改systemd服务的Type类型(最简单)

编辑/lib/systemd/system/python.service,把Type=notify改成Type=simple:

[Service]
# 替换原Type=notify为下面这行
Type=simple

然后重新加载配置并重启服务:

systemctl daemon-reload
systemctl restart python

Type=simple是systemd默认类型,适用于前台运行的程序,systemd会在启动进程后直接认为服务就绪,不会等待额外通知,这样执行systemctl start就不会卡住了。

方案二:让Python脚本支持systemd的notify机制(适合需要精准控制就绪状态的场景)

如果一定要保留Type=notify,需要在Python脚本中添加向systemd发送就绪信号的代码:

  1. 安装systemd-python库(不同发行版安装命令不同):
# Debian/Ubuntu系
sudo apt install python3-systemd
# RHEL/CentOS系
sudo dnf install python3-systemd
  1. 修改你的脚本(注意服务配置里写的是server.py,要保证文件名和路径一致),添加就绪通知:
from http.server import HTTPServer, BaseHTTPRequestHandler
from systemd.daemon import notify

class Serv(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path = '/index.html'
        try:
            file_to_open = open(self.path[1:]).read()
            self.send_response(200)
        except FileNotFoundError:
            file_to_open = "Not Found!"
            self.send_response(404)
        self.end_headers()
        self.wfile.write(bytes(file_to_open, 'utf-8'))

httpd = HTTPServer(('0.0.0.0', 8000), Serv)
# 向systemd发送就绪通知
notify("READY=1")
httpd.serve_forever()
  1. 重新加载配置并重启服务:
systemctl daemon-reload
systemctl restart python
额外注意事项
  • 检查服务配置的ExecStart路径:你提到脚本是script.py,但服务文件里写的是/home/python/server.py,要保证文件名和路径完全匹配,否则服务会启动失败。
  • 建议将自定义服务文件放在/etc/systemd/system/目录下,而非/lib/systemd/system/——后者是系统默认服务的存放目录,自定义服务放在/etc/下更便于管理,且不会被系统更新覆盖。

内容的提问来源于stack exchange,提问作者Saeed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 11:40:03