Shell commands in IPython#
The IPython Notebook allows simple UNIX/Linux commands to be executed in a single input cell. There are no limits but when using, please keep in mind that in contrast to a regular UNIX/Linux shell, start each shell command with a !
, for example !ls
for the command ls
(see below for further explanations about the command). Furthermore, each shell command is executed in its own subshell. For this reason, the results of previous shell commands are not available to you.
To begin with, the command ls
lists the files in the current working directory. The output is shown below the input cell, and lists the single file shell.ipynb
:
[1]:
!ls
debugging.ipynb myscript.py
display.ipynb shell.ipynb
examples.ipynb start.rst
extensions.rst tab-completion-for-anything.png
importing.ipynb tab-completion-for-modules.png
index.rst tab-completion-for-objects.png
magics.ipynb unix-shell
mypackage
The command !pwd
displays the path to working directory:
[2]:
!pwd
/Users/veit/cusy/trn/Python4DataScience/docs/workspace/ipython
The command !echo
outputs text given as parameter to the echo
command. The example below demonstrates how to print Hello world
:
[3]:
!echo "Hello world!"
Hello world!
Passing values to and from the shell#
There is a clever way through which you can access the output of a UNIX/Linux command as a variable in Python. Assign the output of a UNIX/Linux command to a variable as follows:
[4]:
contents = !ls
Here the Python variable contents
has been assigned the output of the command ls
. As a result, contents
is a list, where each list element corresponds to a line in the output. With the print
command you output the list contents:
[5]:
print(contents)
['debugging.ipynb', 'display.ipynb', 'examples.ipynb', 'extensions.rst', 'importing.ipynb', 'index.rst', 'magics.ipynb', '\x1b[34mmypackage\x1b[m\x1b[m', 'myscript.py', 'shell.ipynb', 'start.rst', '\x1b[31mtab-completion-for-anything.png\x1b[m\x1b[m', '\x1b[31mtab-completion-for-modules.png\x1b[m\x1b[m', '\x1b[31mtab-completion-for-objects.png\x1b[m\x1b[m', '\x1b[34munix-shell\x1b[m\x1b[m']
You will see the same result below when executing the pwd command. The current directory is stored in the variable directory:
[6]:
directory = !pwd
[7]:
print(directory)
['/Users/veit/cusy/trn/Python4DataScience/docs/workspace/ipython']