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
3
  • 1
    you would probably use systemd init script with restart: always Commented Oct 20, 2022 at 5:27
  • 1
    You might want to update the title of your question as you don't want to "autostart" but to monitor and automatically restart your program. You might also want to add Linux tag. Commented Oct 20, 2022 at 10:28
  • There are tools that do that for you, nothing to program yourself. Commented Oct 21, 2022 at 7:17

2 Answers 2

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/
Sign up to request clarification or add additional context in comments.

9 Comments

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 What is your ExecStart= ? I think this problem is about paths. You can create a bash script, which first cd <PATH> then next line run the python script. Then use that bash script in ExecStart= instead of the python code directly. look here: caronteconsulting.com/en/news/run-script-python-service
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.
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 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.
|
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.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.