3

I have a simple python file(no GUI) that I'd like it to run in the background at start-up of raspberry pi 3b. I checked out this post Execute script on start-up But it didn't specify what to do with python file though. Python script:

import time
import pygame
pygame.init()
pygame.mixer.init()
while True:
    sounda=pygame.mixer.Sound("test.wav")
    sounda.play()
    time.sleep(5)

The complete file is at: https://github.com/adafruit/Adafruit_Python_MPR121/blob/master/examples/playtest.py However I'm unable to make it work, so just used a simpler version instead. Appreciate the help.

Ingo
  • 42,107
  • 20
  • 85
  • 197
June Wang
  • 241
  • 1
  • 4
  • 11
  • posted the wrong thread location. That script wasn't the one I was looking at. – June Wang Jul 13 '18 at 02:35
  • DO NOT put ANYTHING in .bashrc - this is extremely poor practice as it will run EVERY time you execute a non-login shell. It is intended to initialise the shell. The other suggestions are obsolete SysV code. – Milliways Jul 13 '18 at 03:04
  • That's why I'm asking here for another solution. – June Wang Jul 13 '18 at 03:17
  • There are Hundreds (if not thousands) of similar questions on this site. Have you looked? Unfortunately many wrong or obsolete - even then IT DEPENDS on the script - the question is unanswerable without. – Milliways Jul 13 '18 at 03:37
  • Just added script, and yes I have looked. The variety of solutions confused me. – June Wang Jul 13 '18 at 03:39
  • i'd recommend taking a look at this ... you want to put your python script launch command in /etc/rc.local (since its been a while since i last used that, i am not sure if it is still the recommended way) – Shreyas Murali Jul 13 '18 at 03:58

1 Answers1

2

A systemd unit will do the job. Create a new one with:

rpi ~$ sudo systemctl --force --full edit myPythonScript.service

In the editor insert these statements, save it and quit the editor:

[Unit]
Description=running my python script
Wants=multi-user.target
After=multi-user.target

[Service]
User=pi     # or must it run as root? Then omit this line
ExecStart=/home/pi/myPythonScript.py   # or where your program is

[Install]
WantedBy=multi-user.target

Enable the new service:

rpi ~$ sudo systemctl enable myPythonScript.service

reboot.

Check with:

rpi ~$ systemctl status myPythonScript.service
rpi ~$ systemctl cat myPythonScript.service

Edit again with:

rpi ~$ sudo systemctl --full edit myPythonScript.service

I don't know if it runs on the first attempt. There may be some edge conditions I don't know, something like user rights, environment etc. It is no problem to configure these dependencies. The problem is to find them ;-) Give me a comment under this answer if it doesn't run at first go.

Ingo
  • 42,107
  • 20
  • 85
  • 197