在Linux系统中,将Python文件设置为自启动服务可以让Python脚本在系统启动时自动运行,无需手动启动。这对于需要在系统启动时运行特定任务或服务的应用程序非常有用,例如数据处理任务、定时任务、监控服务等。通过将Python脚本设置为自启动服务,可以确保在系统重启或启动时,相关任务能够自动执行,提高系统的自动化程度和稳定性。
1、新建Python文件
test.py文件内容
print("test service ")
2、新建启动文件
testservice.sh
#!/bin/sh
python3 test.py
3、新建启动服务
/usr/lib/systemd/system/testservice.service
[Unit]
Description=testservice
After=network.target
[Service]
ExecStart=/path/testservice.sh
[Install]
WantedBy=default.target
4、服务自启动
sudo systemctl enable testservice.service
sudo systemctl start testservice.service
sudo systemctl status testservice.service
sudo systemctl restart testservice.service
注:如用宝塔python项目需要注意虚拟目录解析器是:
/www/server/pyporject_evn/test_venv/bin/python3