I wrote a python program that I want to execute on boot, but it HAS to be executed as root, and I don't know how. What are the things I need to do to achieve this? Where should I put the file(the script is in a folder with the necessary python packages) so it runs on boot? How do I run the file as root? Whether it is to put the python folder in a certain directory, use another script to execute the python script, or another way, please share your solutions! I'm doing it on a Raspberry Pi, so the OS is Linux.
The easiest way is to create a systemd service that might look like:
[Unit]
Description=Some python script
After=network.target
[Service]
ExecStart=/usr/bin/python3 script.py
WorkingDirectory=/path/to/scriptdir
StandardOutput=inherit
StandardError=inherit
Restart=always
User=root
[Install]
WantedBy=multi-user.target
You should save this in /etc/systemd/system/servicename.service where servicename can be anything, then set it to run on startup with sudo systemctl enable servicename.service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With