I have been using Jupyter Notebook instead of PowerPoint slides for some of the advanced courses ROI offers. Notebook have a lot features that make teaching much more interactive and productive.

As with any large package, there are things I would like to do that are not instantly available and a workaround needs to be created. This is a short blog of one such workaround.

The original Introduction to Machine Learning course had some 40 to 50 Python scripts showing how the different models work. (The current version has been divided into two different courses each with about 40 Python scripts.)  All of the scripts were designed and tested using scikit-learn.org tools with Anaconda 3’s Python on the bash command line and in Python 3 notebooks. We found only one glitch in moving to using %run cells inside of a Jupyter Notebook.

The program in Figure 1 has been modified for this blog post to show only the glitch being addressed.

This script displays the graphic in a separate window and writes to the command line the prompt “Press enter key to exit!” When showing multiple graphics, “exit” was replaced with “continue.”

When the code is moved to a Jupyter Notebook, the code works the same. See Figure 2: graphic.py Execute in Jupyter Notebook.

Jupyter displays the prompt, “Press enter key to exit!” followed by an input box.

The green arrow points to the * which indicates the program has not terminated. This is expected, as the program is waiting for the enter key to be tapped. All is more or less fine.

However, the question is, “Why the “Press enter key to exit!”? This is confusing, since we don’t know if the script exits or does Jupyter exit the notebook? This question is not needed so let’s get rid of it.

Remove line 36, the input line, and the program terminates and Jupyter moves to the next cell. Not so fine. I now have two different programs, one for the bash command line and one for the cell environment in Jupyter.

We need some way to tell what environment we are in. There are two solutions for this; both a little off the normal path.

The first one is to use a small function to check if sys.stdout is attached to a tty (terminal interface).  See Figure 3: is_command_line()

The try except block is needed as Jupyter Notebook does not implement .fileno().

The second one is to see if program is running interactively under ipython.  See Figure 4: is_ipython()

This one depends on get_ipython.config being False if the script is not running under ipython. The try except block is needed because get_ipython is not available when running python.

Both ways work. They are equally “hacky”. They should only be used if the environment is being changed. Which one to use will depend on the aims of the script.

 

Leave a Reply

Your email address will not be published.