在 Ubuntu 下,如果你已经安装了 Python,你可以使用 systemd 来创建和管理一个 Python 服务。以下是如何创建和启动一个 Python 服务的步骤:
chmod 命令来更改权限:chmod +x /path/to/your/python_script.py
/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 脚本的路径。
sudo systemctl daemon-reload
sudo systemctl start my_python_service
sudo systemctl status my_python_service
如果一切正常,你的 Python 脚本现在应该服务运行。
sudo systemctl enable my_python_service
sudo systemctl stop my_python_service
sudo systemctl restart my_python_service
请注意,这些步骤适用于 Python 3。如果你使用的是 Python 2,请将 /usr/bin/python3 替换为 /usr/bin/python2。