从网上找了好多的方法,有的可以,有的不可以,我这里就不多说。实际我们会一种就可以了,这里我选择我服务自启来记录一下。
一、写py文件
将文件保存在桌面,执行程序会在桌面生成一个aa.txt文件
def w_file(filepath):
with open(filepath,'w') as wf:
wf.write('today is a nice day\n')
w_file('/home/pi/Desktop/aa.txt')
print('succee\n')
二、服务自启
1.在下面的目录中新建一个服务文件
记得这个服务文件的后缀为.service,名称随意。
sudo nano /etc/systemd/system/test.service
2.在这个文件中添加内容
[Unit]
Description = test deamon
After = rc-local.service
[Service]
Type = simple
User = root
Group = root
WorkingDirectory = /home/pi/Desktop
ExecStart = /usr/bin/sudo python3 test.py
Restart = always
[Install]
WantedBy = multi-user.target
Description:描述这个服务的内容
After :告诉脚本在何时运行
Type = simple 告诉systemd该命令再由其开启的话会继续运行
User: 用户超级用户
WorkingDirectory:工作的目录,要启动的文件的目录
ExecStart:要执行的程序
#!/usr/bin/python 用来告诉操作系统运行这个脚本所使用的程序,如果不确定,可以在终端输入which python便可得知。
which python
3.关于服务的操作
开启服务
sudo systemctl start test.service
查看服务的状态
sudo systemctl status test.service
停止服务
sudo systemctl stop test.service
查看服务的输出
journalctl -u test -e
4. 开机自启
使能服务
sudo systemctl enable test.service
失能服务
sudo systemctl disable test.service
5.重启树莓派
我们重启树莓派
sudo reboot
会发现在桌面上生成了一个aa.txt文件
三、更多启动方法
参考下面的连接,里面也有更详细的方法
更多方法