user5740843 user5740843 - 3 months ago 9
Python Question

Starting and stopping subprocess with Python

I'm trying to start and stop a program on a device through

MQTT
commands, but it's not really working out the way I'm hoping..

To start the process, I'm using:

p = subprocess.Popen(["sh", "process.sh"])


Which works out fine, it starts the program.

Further down the line in the code I'm trying to kill/terminate the program with either
p.kill
or
p.terminate
but it's returning the code:

p.terminate()
UnboundLocalError: local variable 'p' referenced before assignment


The code I'm working with is my own, and goes as follows:

def on_message(client, userdata, msg):
if msg.payload == "start":
p = subprocess.Popen(["sh", "stream.sh"])
if msg.payload == "stop":
p.terminate()

Answer
p = None

def on_message(client, userdata, msg):
    global p
    if msg.payload == "start":
            p = subprocess.Popen(["sh", "stream.sh"])
    if msg.payload == "stop" and p:
            p.terminate()