Background script only works when BGE player stops I want to run a thread in the background of the BGE, that retrieves accelerometer data from a LoPy, and uses the values to rotate the object. 

For now, the code I have can only receive and print the data in the console, however the thread itself only runs when I exit the blender game engine. This is my code:

print("---------------------------------------------")
print("Begin collection")

import serial, threading, keyboard

port = 'COM5'

def acc_data(ser):
    while True:
        if keyboard.is_pressed(' '): 
            print('The script was interrupted!')
            break
        raw = ser.readline().decode("utf-8")
        data = raw.split(",")
        try:
            pitch = float(data[0])
            roll = float(data[1])
            print(str(pitch) + " " + str(roll))
        except:
            print("Only one value read")


def acc_thread():
    acc_data(serial.Serial(port, 115200))


try:
    thread = threading.Thread()
    thread.run = acc_thread
    thread.start()
except:
    print("Unable to connect")

print("End collection")


This is the logic editor:



blender console print data
I found out that you can make the script run in a loop by doing this:



Which allowed me to remove the thread and the infinite loop from my code:

print("---------------------------------------------")
print("Begin collection")

import serial

port = 'COM5'

def acc_data(ser):
    raw = ser.readline().decode("utf-8")
    data = raw.split(",")
    try:
        pitch = float(data[0])
        roll = float(data[1])
        print(str(pitch) + " " + str(roll))
    except:
        print("Only one value read")


try:
    acc_data(serial.Serial(port, 115200))
except:
    print("Unable to connect")


print("End collection")


This is what is printed in the console: