0

I'm writing a Python script that takes action when I press a key on my MIDI keyboard:

# https://github.com/superquadratic/rtmidi-python/

import rtmidi_python as rtmidi

def callback(message, time_stamp):
    print message, time_stamp

midi_in = rtmidi.MidiIn()
midi_in.callback = callback
midi_in.open_port(0)

# do something else here (but don't quit)

Now, how to keep the script alive, so that it responsively handles callbacks, while at the same time not draining unnecessary CPU by spinning its wheels?

From my early Visual Studio days I remember a 'while( true ) { doevents(); }' type construct -- the operating system cycles through active processes allocating a certain time slice to each, and this command simply returns control to the scheduler.

But I am on OSX, and I would like to make a platform independent Python script.

Can I?

Bach
  • 6,145
  • 7
  • 36
  • 61
P i
  • 29,020
  • 36
  • 159
  • 267

1 Answers1

0
while True:
    dance_the_merry_dance()
    if should_exit():
        break

Use a while true. You could have it block on events, or even use select if you have file handles.

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
  • 1
    Isn't this inefficient in terms of CPU? It is just going to waste cycles spinning on the exit condition... Doesn't this risk lagging the system? – P i Feb 21 '14 at 21:09