1

Why does my python script work in Thonny but not from the console? (And yes I've tried running it from the console using python3.) Does Thonny run it in a loop that the console doesn't? Thank you.

# Copyright 2019 PK Holdings LLC

import RPi.GPIO as GPIO
from gpiozero import Button
from time import sleep
import sys
import gpiozero
import threading

# Pin Definitions
buttonPin = 17 # Broadcom pin 17

global alarm_running
alarm_running = False

def run():
    # This function sounds the audio alarm(s).
    # Set up Sound
    global alarm_running
    while True:
        print("ALARM RUNNING")
        sleep(2)
        if not alarm_running:
            break

def quiet_audio_alarm():
    global alarm_running
    alarm_running = False

def contact_made():
    # This function is called when contact is made between the leads.
    global alarm_running
    alarm_running = True
    global thread1
    thread1 = threading.Thread(target = run)
    thread1.start()

def no_contact():
    quiet_audio_alarm()
    global alarm_running
    alarm_running = False
    # This join should kill the thread thread1.
    global thread1
    thread1.join()
    print("ALARM STOPPED")

print("Assigning button")    
button=Button(17)
print("Assigning pressed function")
button.when_pressed = contact_made
print("Assigning release function")
button.when_released = no_contact
5

When you run it from the console, the script reaches the end and exits.

Thonny, Mu and IDLE all keep your script running even though it's reached the end.

It's the #1 FAQ on the gpiozero docs: https://gpiozero.readthedocs.io/en/stable/faq.html#how-do-i-keep-my-script-running

You need to use signal.pause() from the standard library to keep the script running, e.g.

from gpiozero import Button
from signal import pause

btn = Button(2)

btn.when_pressed = lambda: print("hello")

pause()
  • Once again, I have learned something :) Good work! – Seamus Nov 25 '19 at 22:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.