在Ubuntu中,将Python脚本作为后台服务可通过systemd管理。先为脚本添加执行权限,再创建服务文件并配置User、Group、ExecStart等参数,然后重载配置、启动服务,检查状态为active即可。可设置开机自启,支持停止、重启操作。
Ubuntu下Python安装后如何启动服务
作者:技术拾光
时间:2026-07-31
浏览:95
文章目录
在 Ubuntu 系统中,若已安装 Python 并希望将脚本作为稳定后台服务运行,最可靠的方法是通过 systemd 进行管理。以下为具体操作步骤,请按顺序执行。

第一步:为脚本添加执行权限
使用chmod 命令为 Python 脚本赋予可执行权限:
chmod +x /path/to/your/python_script.py
第二步:创建 systemd 服务单元文件
使用nano 或 vim 编辑器在 /etc/systemd/system/ 目录下新建服务文件,例如 my_python_service.service,并写入以下内容:
[Unit]
Description=My Python Service
After=network.target
[Service]
Type=simple
User=
Group=
WorkingDirectory=/path/to/your/script/directory
ExecStart=/usr/bin/python3 /path/to/your/python_script.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
请将 和 替换为实际运行脚本的用户和组,同时将 /path/to/your/python_script.py 替换为脚本的真实路径。
第三步:重新加载 systemd 配置
执行以下命令使新创建的服务文件生效:sudo systemctl daemon-reload
第四步:启动服务
使用systemctl start 命令启动服务:
sudo systemctl start my_python_service
第五步:检查服务运行状态
通过systemctl status 查看服务是否正常运行:
sudo systemctl status my_python_service
若输出显示 active (running),则表示脚本已成功启动。
第六步:设置开机自启(可选)
如需让服务在系统启动时自动运行,执行:sudo systemctl enable my_python_service
第七步:停止或重启服务
使用以下命令分别停止或重启服务:sudo systemctl stop my_python_service
sudo systemctl restart my_python_service
注意事项
以上步骤默认使用 Python 3(路径为/usr/bin/python3)。若环境仍使用 Python 2,请将 ExecStart 中的路径改为 /usr/bin/python2。实用工具推荐
电子包浆
使用 ›绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
图片压缩
使用 ›选择画质和输出格式,预览压缩前后的大小。