1

I know how to autostart a python script (or so I thought). But I want a programm or something, if my python script is not running anymore, it should start the script again. Has anyone a idea how to do this? Edit: I tried running it as a service but that didnt work.

import bluetooth
import pygame
pygame.mixer.init()
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
port = 22
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print ("Verbindung Hergestellt mit: ", address)
while True:
    recvdata = client_sock.recv(1024)
    print ("Nachricht bekommen: %s" % recvdata)
    pygame.mixer.pause()
    if (recvdata == b"h"):
        sound = pygame.mixer.Sound('/home/maxi/Desktop/test.wav')
        playing = sound.play()
    if (recvdata == b"p"):
        sound = pygame.mixer.Sound('/home/maxi/Desktop/test2.wav')
        playing = sound.play()
    if (recvdata == b"k"):
        break
client_sock.close()
server_sock.close()

My startscript is:

[Unit]
Description=MaxiTest
After=multi-user.target



[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/python3 /home/maxi/Desktop/btsound1.py



[Install]
WantedBy=multi-user.target
Ponda
  • 9
  • 4

2 Answers2

1

You can search more about how a python script can perform as a service or daemon. There are many solutions in this link:

How to make a Python script run like a service or daemon in Linux

Between all solutions, I prefer 3 of them (I'm not very familiar with raspberry-pi, so check compatibility):

  1. Cronjob: You can create a cronjob for the script and the OS will run it every x seconds/minutes/... automatically and periodically.

  2. Systemctl/Systemd: Create a custom service file for your script and start and enable it in Systemd. A complete guide is here: https://medium.com/codex/setup-a-python-script-as-a-service-through-systemctl-systemd-f0cc55a42267

You chose systemd (after editing); In /PATH_project/ create 2 bash scripts like this:

#!/bin/bash
# This is start.sh
cd /home/maxi/Desktop/
/usr/bin/python3 btsound1.py

And create stop.sh:

#!/bin/bash
for KILLPID in `ps ax | grep ‘myservice’ | awk ‘{print $1;}’`; do
kill -9 $KILLPID;
done

Then give execution permission to both files using:

chmod a+x start.sh
chmod a+x stop.sh

Then create a myservice.service file in /etc/systemd/system :

[Unit]
Description=myservice service
Wants=network-online.target
After=network.target network-online.target

[Service]
Type=simple
Restart=always
ExecStart=/bin/bash /home/maxi/Desktop/start.sh
ExecStop=/bin/bash /home/maxi/Desktop/stop.sh
RestartSec=5
TimeoutSec=60
RuntimeMaxSec=infinity
PIDFile=/tmp/mydaemon.pid

[Install]
WantedBy=multi-user.target

Then:

sudo systemctl daemon-reload
sudo systemctl start myservice.service
sudo systemctl status myservice.service

Benefits of using such bash scripts is that you can handle some more things in this way. For example if you are using a virtual environment, you can use source activate in start.sh file before running the script.py .

  1. Supervisord: Install Supervisor and create a supervisord.conf file for your script. A good guide is here: https://csjourney.com/managing-processes-with-supervisor-in-depth-tutorial/
Omid Estaji
  • 303
  • 5
  • 10
  • I tried using the systemctl. My bluetooth client is connecting to the device but it is not playing sound. When I start the script normally it is working. – Ponda Oct 20 '22 at 09:55
  • @Ponda What is your ExecStart= ? I think this problem is about paths. You can create a bash script, which first cd then next line run the python script. Then use that bash script in ExecStart= instead of the python code directly. look here: https://www.caronteconsulting.com/en/news/run-script-python-service/ – Omid Estaji Oct 20 '22 at 10:08
  • I edited the main question. There you can see now the script and updated question. I tried the bash technique but seems like it has the same habit like autostarting it directly with python. (Client connects but the raspi is not outputting sound) I dont want to use cronjob because I only want to restart the script when it failed. With cronjob the device would disconnect like every 10 minutes from the client. Thats not what I want. – Ponda Oct 20 '22 at 11:27
  • So I put everything into 1 shell script (preparing de port and starting the script) if I run it via terminal it is working without a problem. But If I try systemd, it wont output sound. And when my bluetooth connection is failing I want to restart the application. The python script is closing with a error when the devices dissconnect. – Ponda Oct 21 '22 at 08:05
  • @Ponda Do you have any log or error? Are you sure about using correct Python interpreter(/usr/bin/python3)? For example if you are using a virtual env or more than one Python interpreter on the device, you should exactly use the interpreter with enough permission or correct packages. – Omid Estaji Oct 21 '22 at 08:12
  • if I start the start.py script with ./start.py it is working without any problem so I think the start script is done correctly. But as soon I want to start the service it wont work. The client connects and can send data, but nothing will happen. I dont have any logfile or it isnt known to me. – Ponda Oct 21 '22 at 09:44
  • ^^ no sound wil be outputted when it is started as a service. I dont have much knowledge about linux / raspberry so I really have no Idea what the problem could be. – Ponda Oct 24 '22 at 12:13
  • about the stop.sh script. My serrvice is working but not right. I cant stop the service... – Ponda Oct 25 '22 at 06:05
  • @Ponda I think you should create a log file and add debugging to your code for more details. – Omid Estaji Oct 27 '22 at 17:51
0

I found what was the problem. I used rc.local and started the program 10 seconds after boot. The system needed time first to set up before I could start the script.

Ponda
  • 9
  • 4
  • I'm happy you can solve the problem, very well. Now you can check systemd/systemctl method using a ExecStartPre=/bin/sleep 10 which make delay then the service will run. Goodluck friend. – Omid Estaji Oct 28 '22 at 12:24
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 01 '22 at 02:17