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()
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()
You have to define p as global
def on_message(...):
global p
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.