linux开机执行python脚本


一、利用init
1、系统有相应的python解释器,并在脚本头部声明,例如:#!/usr/bin/python
2、给予该脚本可执行权限,如:chmod +x somescript.py
3、脚本接受第一个命令参数,需要能接受至少包含start的参数,至于stop、restart以及status等并不是必须的,你可以自己来扩展。如: ./somescript.py start 这种命令格式来启动程序
4、将该脚本放到/etc/rc.d/init.d/路径下
5、chkconfig --add somescript.py添加服务
6、chkconfig --level 3 somescript.py on   在init为3或5的级别上开机启动该服务

在运行chkconfig时,程序会报错,需要在文件中加入:

1 #chkconfig:- 85 15
2 #description:xxxx is a service

 

建议将init级别设置为3,因为设置为5时,会运行两次脚本。

后期发现,级别3也存在同样的问题。

二、利用systemd

编写device.service脚本

 
 1 [Unit]
 2 Description=xxxx
 3 After=network.service
 4  5 [Service]
 6 Type=simple
 7 User=root
 8 Group=root
 9 WorkingDiretory=/var/www/html/app10 ExecStart=/usr/bin/python app.py
11 12 [Install]
13 WantedBy=multi-user.target

 

将该脚本复制到/etc/systemd/system/,将app.py脚本赋予执行权限:

1 chmod +x app.py

 

启动服务:

 
1 systemctl start app.service

 

查看服务状态:

 
1 systemctl status app.service

 

停止服务:

 
1 systemctl stop app.service

 

大功告成!!!

现在Linux平台大都提供systemd,个人推荐使用systemd。systemd教程请移步阮一峰的教程


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM