python - Autostarting Python scripts on boot using crontab on rasbian
问题描述
I am a pretty new python programmer and am a little bit familiar with crontab. What I am trying to do is probably not the best practice but it is what I am most familiar with.
I have a raspberry pi with a couple python scripts I want to run on boot and stay running in the background. They are infinite loop programs. They are tested and working in a cmd terminal and have been function for a couple weeks. Just getting tired on manually starting them up. When the pi goes through a power cycle.
So I did a sudo crontab -e
and added this line as my only entry
@reboot /usr/bin/python3 /usr/bin/script.py &
If I copy paste this exactly (minus the @reboot) it will run successfully in the cmd line.
I am using a cmd:
pgrep -af python
to check to see if it is running. I normally see two scripts running there but not the one I am trying to add.
I am not sure where I am going wrong or my best method to troubleshoot my issue. From the research I have been doing it seems like it should work.
Thanks for your help Kevin
解决方案
You might find it easier to create a systemd service file for each program that you want to start when you Raspberry Pi boots. systemd comes with a few more tools to help you debug your configuration.
This is what an example systemd service file (located at /etc/systemd/system/myscript.service
) would look like:
[Unit]
Description=My service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /usr/bin/script.py
WorkingDirectory=/home/pi/myscript
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi
[Install]
WantedBy=multi-user.target
and then you can enable this program to run on boot with the command:
sudo systemctl enable myscript.service
These examples are from Raspberry Pi's documentation about systemd. But because systemd is widely used in the Linux world, so you can also follow documentation and StackOverflow answers for other Linux distributions.
推荐阅读
- php - 仅当出现“,”时才拆分数组
- matlab - 用于远程函数调用的最简单的网络协议?
- python - bazel 3.7.2 上用于在 MAC M1 上设置媒体管道的替代类型“darwin-arm64”可能是什么?
- php - 在 PHP 升级到 PHP8 之前识别类型杂耍问题
- php - 如何在同一网站的不同页面上使用具有相同密钥的 recaptcha?
- json - Azure DevOps 发布管道中如何使用基于环境的逻辑应用(单租户)项目的connections.json文件
- c++ - 查找适用于 HWND 的 RealTimeStylus
- ios - 如何从html字符串中删除所有标签?
- node.js - mongodb通过多个条件和一个结果nodejs多次查找
- python - 我正在尝试使用 python tkinter 模块将数据添加到 MysqlDB 中的表中。我创建了一个输入数据的用户界面。但它没有显示在数据库中