如何将自定义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发送就绪信号的代码:
- 安装
systemd-python库(不同发行版安装命令不同):
# Debian/Ubuntu系 sudo apt install python3-systemd # RHEL/CentOS系 sudo dnf install python3-systemd
- 修改你的脚本(注意服务配置里写的是
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()
- 重新加载配置并重启服务:
systemctl daemon-reload systemctl restart python
额外注意事项
- 检查服务配置的
ExecStart路径:你提到脚本是script.py,但服务文件里写的是/home/python/server.py,要保证文件名和路径完全匹配,否则服务会启动失败。 - 建议将自定义服务文件放在
/etc/systemd/system/目录下,而非/lib/systemd/system/——后者是系统默认服务的存放目录,自定义服务放在/etc/下更便于管理,且不会被系统更新覆盖。
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

