Skillversitas

IPython System Commands

Inside IPython, prefixing a line with an exclamation mark runs the rest of that line in the operating system shell: !ls on Linux and macOS, !dir on Windows. Your keyboard's up-arrow history, tab completion on file names, and magic commands all keep working while you hop between the Python and system environments, so directory juggling no longer requires leaving the session.

Capturing Shell Output

The result of a shell command lands in a special CmdOutput object and can be assigned to a Python variable for further processing:

In [1]: files = !ls

In [2]: files
Out[2]: ['analysis.ipynb', 'weights.py', 'notes.md']

In [3]: filtered = [f for f in files if f.endswith('.py')]
In [4]: filtered
Out[4]: ['weights.py']

Because the output behaves like a list of lines plus a .s attribute holding the whole text, it works everywhere a sequence does.

Passing Python Values In

Anything inside the command surrounded by braces interpolates Python variables into the shell line, which makes templated commands easy — for example, feeding a generated file name to a utility or looping in the shell while Python provides the values:

In [5]: report = 'results-2026.txt'

In [6]: !cp {report} archive/
In [7]: !wc -l {report}

The two dollar signs $$var exist for shell syntax where a single $ would otherwise collide with environment variables.

A set of magics covers the most common file-system chores so they work the same on every platform. %pwd prints the shell's working directory, %cd changes it (and can be given .., absolute paths, or bookmark names via %bookmarks), and object autocompletion helps you build the command line:

In [8]: %pwd
Out[8]: '/home/user/project'

In [9]: %cd data
/home/user/project/data

In [10]: %dhist                 # history of visited directories
Directory history:
 0: /home/user/project
 1: /home/user/project/data

When to Use ! Versus Magics

Prefer ! for one-off commands and utilities such as git, scp, or build scripts; prefer magics for things you want portable across platforms and integrated into scripts. Both coexist happily in the same workflow, and inside notebooks each system call appears as a cell output showing the standard output and error of the process.

Summary

Escape to the OS with !command, capture the result as a Python list-like object, interpolate values with {var}, and use %cd, %pwd, and %dhist for portable directory management.