'saving data from .py script into a file via linux service

Using RPi I am sending and receiving data to and from ESP32 at the same time. I have two .py scripts and two linux services. Before I created the services the .py scripts were working correctly (but not at the same time, thats why I am making services), the rec_data.log contained data from ESP32. They work parallely (checked via systemctl status for both services), also ESP32 is getting the message from RPi. But the part with saving data from ESP into a .log file on RPi is not working. I used StandardOutput=... and the rec_data.log file is getting created, but remains empty.

My service looks as follow:

 GNU nano 5.4                             receive.service                                       [Unit]
Description=Test Service
#After=multi-user.target
#[email protected]

[Service]
#Type=simple
ExecStart=/usr/bin/python3 /home/pi/receive.py
StandardOutput=append:/home/pi/rec_data.log # tried without these two lines also (didnt work)
StandardError=append:/home/pi/rec_err.log # tried without these two lines also (didnt work)
#Restart=always
#StandardInput=tty-force

[Install]
WantedBy=multi-user.target

My .py script looks as follow:

    GNU nano 5.4                                receive.py                                         from bluetooth import *
file = open("rec_data.log", "a") // tried to give the full path to the file also (didnt work)
def rx_and_echo():
    while True:
        data1 = sock.recv(buf_size)
        if data1:
            data1 = str(data1)
            data1 = data1[2:-1]
            file.write(data1 + '\n')

addr = "E0:E2:E6:CF:BB:AA"
service_matches = find_service(address=addr)
buf_size = 1024

if len(service_matches) == 0:
    print("couldn't find the SampleServer service =(")
    sys.exit(0)

first_match = service_matches[0] 
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]

port = 1 
sock = BluetoothSocket(RFCOMM)
#sock.connect((host, port)) // this is done on send.py so cannot be doubled here

rx_and_echo()
file.close()
sock.close()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source