商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > ubuntu下python安装后如何启动服务

ubuntu下python安装后如何启动服务

  发布于2026-07-31 阅读(0)

扫一扫,手机访问

在 Ubuntu 系统中,如果你已经装好了 Python,想让某个脚本像个正经的后台服务一样跑起来,最靠谱的办法就是交给 systemd 来管理。下面直接上操作,跟着走就行。

ubuntu下python安装后如何启动服务

  1. 第一步,先给你的 Python 脚本加上执行权限。用 chmod 搞定:
chmod +x /path/to/your/python_script.py
  1. 接着,创建一个 systemd 服务文件。用 nanovim 打开一个新文件,路径为 /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 换成脚本的真实路径。

  1. 然后,让 systemd 重新加载配置:
sudo systemctl daemon-reload
  1. 启动刚定义的服务:
sudo systemctl start my_python_service
  1. 检查服务是否正常运行:
sudo systemctl status my_python_service

如果状态显示 active (running),说明脚本已经成功跑起来了。

  1. 想让它在系统启动时自动启动?执行:
sudo systemctl enable my_python_service
  1. 需要停止或重启服务,用这两个命令:
sudo systemctl stop my_python_service
sudo systemctl restart my_python_service

最后多说一句:以上步骤默认用的是 Python 3(路径 /usr/bin/python3)。如果你还在用 Python 2,记得把路径换成 /usr/bin/python2

本文转载于:https://www.yisu.com/ask/33232472.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注