【发布时间】:2021-07-13 13:50:31
【问题描述】:
我目前正在通过 Thonny 运行一个程序,并且我想让 pi 在该程序打开时自动启动它。我目前有 pi 4,代码在 Python3 上运行。尝试了许多自动启动的方法,例如使用 rc local 和 bash rc,但似乎都没有。
【问题讨论】:
标签: python python-3.x raspberry-pi raspberry-pi4
我目前正在通过 Thonny 运行一个程序,并且我想让 pi 在该程序打开时自动启动它。我目前有 pi 4,代码在 Python3 上运行。尝试了许多自动启动的方法,例如使用 rc local 和 bash rc,但似乎都没有。
【问题讨论】:
标签: python python-3.x raspberry-pi raspberry-pi4
我建议使用autostart 文件。
编辑以下文件:
sudo nano /etc/xdg/lxsession/LXDE-pi/autostart
默认应该是这样的:
@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@xscreensaver -no-splash
添加命令以使用 @ 前缀运行脚本并保存。新的autostart 文件应如下所示:
@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@xscreensaver -no-splash
@python3 /home/pi/your_script.py
更多信息:https://www.raspberrypi.org/forums/viewtopic.php?t=294014
【讨论】:
通过使用.bashrc 之类的东西,您的程序只会在您打开命令行时执行。
你可以使用systemd services:
/etc/systemd/system/中创建一个文件your_service.service(你需要是root,所以使用sudo)。文件名将是您的服务名称,不带 .service 扩展名(在这种情况下,您的服务将命名为 your_service)[Unit]
Description=A short description of your service
After=network.target # <-- put this if your script needs network, otherwise you can omit this line
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always # use this to always restart the script if the process ends. If your script only needs to run once at startup and is not a daemon, don't use this.
RestartSec=1
User=root # user account used to run the service
ExecStart=python3 /path/to/your/script.py
[Install]
WantedBy=multi-user.target
然后,您可以使用以下命令启动您的脚本:
sudo systemctl start your_service
您终于可以使用以下命令使服务在启动时自动运行:
sudo systemctl enable your_service
您可以在以下链接中找到有关 systemd 服务和所有可用选项的更多文档/教程:
【讨论】:
.bashrc 中的任何命令也会在重启时执行。