Search code examples
pythonlinuxunixraspberry-pistartup

Why is my Python script running twice in the background when I try to execute it at startup of my Raspberry Pi by adding the command to /etc/profile?


Why is my Python script running twice in the background when I try to execute it at startup of my Raspberry Pi by adding the command to /etc/profile?

I have a command written at the end of the file /etc/profile for a Python script to run at startup of my Raspberry Pi, "sudo python /path/filename.py &", and for some reason it runs twice, every time. When I comment the line out and execute it manually from the command line it runs normally. Why does that happen and what can I do to prevent that from happening?

I know for fact that it is running twice in the background because in my code I have a buzzer that beeps twice at times and 3 times at others, and it beeps 4 times instead of 2 and 6 times instead of 3. Also the code ends up contradicting itself, clearly because each script run is trying to do something else at the same time.

Thanks in advance.


Solution

  • I'm answering my own question with a better method for running scripts at boot/startup.

    I'm not exactly sure why this was happening, but I did learn that executing scripts on startup with this method is a bad practice and is best avoided.

    I started using the Crontab instead.

    This is what you need to do:

    crontab -e

    This opens up the crontab, then add the following line:

    @reboot python /filelocation/filename.py

    This will execute the script as soon as the Pi boots up.

    No more double script runs!