IPython As A Shell - First Steps

Now we can start to use IPython as a shell. Start it with our new profile with ipython --profile shell

We can run any command by prefixing it with a ! character.


In [ ]:
!ls -l

You can even put the output into a variable.


In [ ]:
llist = !ls -l

Since assignments don't return a value we get no outut. We can check the value by entering just the variable name.


In [ ]:
llist

Try just ls on it's own'


In [ ]:
llist = !ls

In [ ]:
llist

This is actually a special sort of list, an SList, which has some special properties. If we enter llist.n we will get our list back as a single string with each list item separated by a return character, \n.


In [ ]:
llist.n

We can also get it back with each item separated by a space character.


In [ ]:
llist.s

Or finally we can get it as a list of file paths.


In [ ]:
llist.p

That's pretty good but we can't actually use llist.s as, for example, the arguments to another Unix command because our file names have spaces in them.

How can we fix that? We need to surround each file name with quote character's

We can do it using a special python function, map().

First, let's define a function that does the surrounding.


In [ ]:
def quote(str):
    return '"' + str + '"'

Now we do our map.


In [ ]:
new = map(quote, llist)

In [ ]:
new

Now join our list items with the join function. It starts with the character we use to join.


In [ ]:
them = ' '.join(new)

In [ ]:
them

So now we have our file names each surrounded by double quotes and joined in a string.

We can pass python variables out to a system command.


In [ ]:
!echo $them

If we want to use a system environment variable we have to use two dollar signs.


In [ ]:
!echo $$EDITOR

One small problem using map() to create our new list is that we get a list, not an SList, so we lose the special powers of an SList.

Instead we will use a different method and get an SList.

First, we will import the IPython module so we can use its special functions.


In [ ]:
import IPython

Now we create an empty SList.


In [ ]:
example = IPython.utils.text.SList()

Use for to loop over each item in our list putting it into the variable one and then appending it to our list wrapped in double quotes.


In [ ]:
for one in llist:
    example.append('"' + one + '"')

In [ ]:
example

In [ ]:
example.n

In [ ]:
example.s

Unfortunately the one thing we lose is the path type


In [ ]:
example.p

See, we just get an empty list.


In [ ]: