System commands from IPython

You can make use of your Python skills by interacting with system commands directly for things like file renaming, directory restructuring, or calling any arbitrary system command from within IPython. Here are some ways to do that.

! at the beginning of a line, tells IPython this line is to be sent to the system shell
!ls list directory (the magic function, ls, does the same thing)
patt = ‘*.py’ set up a Python variable, patt, which will be used in the examples below
!ls -l $patt look for .py files using the -l format.  The $ expands
the Python variable to the shell.
!ls -l ${patt+c} adds a c to the end of patt to make ls look for .pyc files.  {} indicates a Python expression
alias shows defined aliases, like ldir or ll
alias pr echo You Said: %s define an alias called pr
pr HELLO prints out “You Said HELLO” (executes the alias)
unalias pr remove the alias pr

Note: The magic command, ls, can also be used to find .py files with the command ls *.py.  However, more advanced usage, like passing Python variables and expressions or using options of the ls command (!ls -lha for example, to list the details of all files, including hidden ones, with human-readable sizes ) need to be done with the system command. The magic command is actually an alias for !ls -F.  Using the system call form is the more general case, and can be used for any system calls.

Define a function to be used in the examples below:

def go(patt):  
    !ls -l $patt   

go(‘*.py’) looks for .py files using the go() function defined above
x = !ls saves a list of the results of the system call to ls
len(x) how many items were in the directory (where x = !ls as above)
x.s displays the contents as a long string
x.l displays as a list
x.n display with newlines
x = !ls *.py | sort a sorted list of items ending with .py in the
directory

Note: the list returned by a system call is not a standard Python list.  Rather, it is a list of type IPython.genutils.SList which has the .s, .l, and other useful methods.  Check out what it can do with x.[tab] (see introspection section, above).

0 Responses to “System commands from IPython”


  • No Comments

Leave a Reply