python_retrieving_shell


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 [ ]:
!hostname

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
host_name

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 [ ]:
type(host_name)

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


In [ ]:
host_name?

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/text.py
Docstring:  
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 path.py package)

Any values which require transformations are computed only once and
cached.

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
dir_list

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


In [ ]:
print(dir_list.n)