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

Ubuntu20.04关机提示等待python进程,求类Docker的.service解决方法

解决Ubuntu 20.04关机时等待Python进程的问题

可以通过创建自定义systemd服务,在关机流程中强制终止所有Python进程,步骤如下:

1. 创建systemd服务文件

在/etc/systemd/system/目录下新建python-shutdown.service文件,写入以下内容:

[Unit]
Description=Force stop all Python processes on shutdown
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target

[Service]
Type=oneshot
ExecStart=/bin/bash -c "pkill -f python || true"
ExecStart=/bin/bash -c "pkill -f python3 || true"
RemainAfterExit=yes

[Install]
WantedBy=shutdown.target reboot.target halt.target
  • DefaultDependencies=no:避免与默认服务依赖冲突,确保该服务在关机流程早期执行
  • Before=...:指定服务必须在关机、重启、halt操作前完成
  • pkill -f python:匹配并终止所有包含python关键字的进程,|| true保证即使没有Python进程也不会触发错误
  • 加入python3是因为Ubuntu 20.04默认使用Python 3,进程名可能为python3

2. 启用并加载服务

执行以下命令使服务生效:

sudo systemctl daemon-reload
sudo systemctl enable python-shutdown.service

3. 优化(可选)

如果仍有残留进程未被终止,可以尝试用强制杀死命令替换原有ExecStart行(注意:强制杀死可能导致数据丢失,仅在必要时使用):

ExecStart=/bin/bash -c "killall -9 python python3 || true"

注意:这种方式会终止所有Python进程,包括后台运行的脚本、服务等。若有需要正常退出的Python程序,建议单独为其配置systemd服务并实现正确的退出逻辑,避免强制终止导致数据损坏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:25:38