Retrieving shell command output in IPython

This demonstration shows how to capture the outputs of Linux commands executed from the Jupyter notebook and store them as Python variables.

We begin by getting the IP address of our host with a Linux command and assigning it to a Python variable. Next we explore the special SList type of the returned results. Then we show how to use one of the special attributes of the SList type to print a formatted directory listing returned by executing the system shell ls -al command.

To execute a Linux command in a code cell we must preface the Linux command with the bang character, !. This tells the IPython REPL to route the command that comes after the '!' to the OS shell.

For example, we can get the hostname of our platform as follows:

In [ ]:

Or if we want the full Internet address, we can execute the following:

In [ ]:
!hostname -I

To capture our host name as a Python variable is straightforward:

In [ ]:
host_name = !hostname

Note the type of the host_name variable returned is special. It is of type SList or to give it its full name IPython.utils.text.SList:

In [ ]:

We can ask for more details about the host_name object as follows:

In [ ]:

The following message appears in a separate window:

Type:        SList
String form: ['plpynqz1']
Length:      1
File:        /usr/local/lib/python3.4/dist-packages/IPython/utils/
List derivative with a special access attributes.

These are normal lists, but with the special attributes:

* .l (or .list) : value as list (the list itself).
* .n (or .nlstr): value as a string, joined on newlines.
* .s (or .spstr): value as a string, joined on spaces.
* .p (or .paths): list of path objects (requires package)

Any values which require transformations are computed only once and

The key observation here is that the SList type is simply a

List derivative with special access attributes

If we execute a shell command which returns multi-line output, type SList captures the output as a list of strings:

In [ ]:
dir_list = !ls -al

So to print dir_list, as a list of strings, separated by newlines, we can run the following:

In [ ]: