An IPython magic for modal notifications

I have been doing some hard-core processing using IPython Notebook. Because of that, I needed to check from time to time if it was finished or not. This led me to think that it would be nice to have a 'big and loud' on-screen notification.

I remembered that IPython Notebook 2.0 uses Bootstrap and decided to make a code a line magic show a model windows with a message of my choice. This would make a great nbextension... but I will leave this for my next afternoon hack.

In [1]:
from IPython.html import widgets
from IPython.display import display
import string
import random

Creating the notification function

In [2]:
def do_notify(line):
    suffix = ''.join(random.choice(string.digits) for _ in range(6)) # a suffix to avoid clashes
    modal = widgets.HTMLWidget(value =
                              '''
                              <div class="modal fade" id="notif_modal_'''+suffix+'''" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
                              <div class="modal-dialog">
                              <div class="modal-content">
                              <div class="modal-header">
                              <button type="button" class="close" data-dismiss="modal"><span aria-hidden="false">&times;</span></button>
                              <h4 class="modal-title" id="myModalLabel">Attention!</h4>
                              </div>
                              <div class="modal-body">'''
                              +line+
                              '''</div>
                              <div class="modal-footer">
                              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                              </div>
                              </div>
                              </div>
                              </div>
                              <script type="text/javascript">
                              $("#notif_modal_'''+suffix+'''").modal('show');
                              </script>
                              ''')
    display(modal)

Registering the functionas a line magic

In [3]:
ip = get_ipython()
In [4]:
ip.register_magic_function(do_notify, 'line', 'notify')

Testing the magic

In [5]:
import time
In [6]:
print('Philosopher sleeping...')
time.sleep(5)
print('Up and hungry...')
%notify Dinner is ready!
Philosopher sleeping...
Up and hungry...
In [7]:
time.sleep(5)
%notify Let's have a coffee