import json
from gpiozero import Button
from time import sleep
from mpd import MPDClient

button = Button(23)
while True:
    if button.is_pressed:
        client = MPDClient()               # create client object
        client.timeout = 10                # network timeout in seconds (floats allowed), default: None
        client.idletimeout = None          # timeout for fetching the result of the idle command is handled seperately, default: None
        client.connect("localhost", 6600)  # connect to localhost:6600
        if (client.status()['state']=="play"):
        print ("State is:")
        print (client.status()['state'])
        client.close()                     # send the close command
        client.disconnect()                # disconnect from the server

I call this script in my bashrc file:

python ~/scripts/gpio/gpiompdstartstop.py &

I tried increasing the sleep time within the cycle, but it doesn't help at all...

I am considering investigating how to use a subprocess call, but I'm not sure it would help, nor how to go about it.

Thank you for any help.

  • 1
    NOTE even with the "fix" this is poor practice. Use a callback or wait for press.
    – Milliways
    Oct 2, 2020 at 22:48
  • Can you elaborate? I have zero knowledge about that. If you can share an example I would appreciate it.
    – Mike
    Oct 5, 2020 at 21:24

2 Answers 2


The sleep is only executed if the button is pressed. You need a sleep between checks for the button press to let other processes run.


while True:
    if button.is_pressed:
        # do work
    time.sleep(0.05) # check for button press 20 times a second.
  • You are absolutely right. I'm an idiot. Added sleep for a second and fixed my issue. At least my first impression was correct, even though I failed to solve the problem. Any idea why there are two processes listed?
    – Mike
    Oct 2, 2020 at 18:21
  • Do you mean Linux processes? There will be the bash shell process and the Python process for your script. The bash shell script will exist until your Python script ends.
    – joan
    Oct 2, 2020 at 19:40
  • Htop shows 2 lines with the same content (the script command): python ~/scripts/gpio/gpiompdstartstop.py & The way I had it before showed a few more repeated ones...
    – Mike
    Oct 5, 2020 at 21:27

GpioZero is far easier for beginners to use (and unlike RPi.GPIO it ACTUALLY has DOCUMENTATION and EXAMPLES)

See the Button class

I would probably use when_pressed. As your code is doing little you could use wait_for_press which will block until needed.

Incidentally calling from .bashrc is an extremely POOR practice. This is designed for configuring the shell NOT running programs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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