温馨提示×

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

小樊
53
2025-09-25 07:44:44
栏目: 编程语言

在 Ubuntu 下,如果你已经安装了 Python,你可以使用 systemd 来创建和管理一个 Python 服务。以下是如何创建和启动一个 Python 服务的步骤:

  1. 首先,确保你的 Python 脚本具有可执行权限。你可以使用 chmod 命令来更改权限:
chmod +x /path/to/your/python_script.py
  1. 创建一个新的 systemd 服务文件。使用文本编辑器(如 nano 或 vim)创建一个新文件,例如 /etc/systemd/system/my_python_service.service。在这个文件中,添加以下内容:
[Unit]
Description=My Python Service
After=network.target

[Service]
Type=simple
User=<your_user>
Group=<your_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

请将 <your_user><your_group> 替换为运行脚本的用户和组。将 /path/to/your/python_script.py 替换为你的 Python 脚本的路径。

  1. 重新加载 systemd 配置:
sudo systemctl daemon-reload
  1. 启动新创建的服务:
sudo systemctl start my_python_service
  1. 检查服务状态:
sudo systemctl status my_python_service

如果一切正常,你的 Python 脚本现在应该服务运行。

  1. 若要使服务在系统启动时自动运行,请执行以下命令:
sudo systemctl enable my_python_service
  1. 如果需要停止或重启服务,可以使用以下命令:
sudo systemctl stop my_python_service
sudo systemctl restart my_python_service

请注意,这些步骤适用于 Python 3。如果你使用的是 Python 2,请将 /usr/bin/python3 替换为 /usr/bin/python2

0