Starting and stopping subprocess with Python
<p>I'm trying to start and stop a program on a device through <code>MQTT</code> commands, but it's not really working out the way I'm hoping..</p>

<p>To start the process, I'm using:</p>

<pre><code>p = subprocess.Popen(["sh", "process.sh"])
</code></pre>

<p>Which works out fine, it starts the program.</p>

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

<pre><code>p.terminate()
UnboundLocalError: local variable 'p' referenced before assignment
</code></pre>

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

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

<pre><code>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()
</code></pre>

python