Start with a simple ls
command.
ls = !ls
Note that the return type is not a simple list
.
type(ls)
IPython.utils.text.SList
It is an SList
, a list-like object that contains "chunks" of stdout
and stderr
, properties for accessing those chunks in different forms, and convenience methods for operating on them.
ls
['conda-bld', 'README.md', 'requirements.txt', 'SList.ipynb']
There are many ways to refer to the output from an SList
as a list-like of strings.
ls == ls.get_list() == ls.list == ls.l
True
Some properties also return the output as a newline delimited string.
print(ls.nlstr)
conda-bld README.md requirements.txt SList.ipynb
ls.get_nlstr() == ls.nlstr == ls.n
True
Other properties return the output as a space separated string.
print(ls.spstr)
conda-bld README.md requirements.txt SList.ipynb
ls.get_spstr() == ls.spstr == ls.s
True
Still other properties return the output as a list of pathlib.Path
instances.
ls.paths
[PosixPath('conda-bld'), PosixPath('README.md'), PosixPath('requirements.txt'), PosixPath('SList.ipynb')]
ls.get_paths() == ls.paths == ls.p
True
import pathlib
isinstance(ls.paths[0], pathlib.Path)
True
These are convenient for performing further path operations in Python.
[p.is_dir() for p in ls.paths]
[True, False, False, False]
SList
objects expose a fields()
method.
df = !df -h
df
['Filesystem Size Used Avail Use% Mounted on', 'overlay 981G 577G 404G 59% /', 'tmpfs 26G 0 26G 0% /dev', 'tmpfs 26G 0 26G 0% /sys/fs/cgroup', '/dev/sda1 981G 577G 404G 59% /etc/hosts', 'shm 64M 0 64M 0% /dev/shm', 'tmpfs 26G 0 26G 0% /sys/firmware']
fields
splits the output into whitespace delimited columns and returns the values of columns, specified by their indices, as space-separated strings.
df.fields(0,4)
['Filesystem Use%', 'overlay 59%', 'tmpfs 0%', 'tmpfs 0%', '/dev/sda1 59%', 'shm 0%', 'tmpfs 0%']
SList
objects also expose a grep()
method. grep
evaluates a regular expression or callable against all elements of the SList
or a whitespace delimited column in each element.
df.grep('dev', field=5)
['tmpfs 26G 0 26G 0% /dev', 'shm 64M 0 64M 0% /dev/shm']
grep(prune=True)
turns the grep into a filtering operation instead of a matching operation.
hosts = !cat /etc/hosts
print(hosts.n)
# Kubernetes-managed hosts file. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 10.12.9.251 jupyter-3675d82eae802db2c011037033d614a5-2dlwedcif3
The return value of grep
(and fields
) is another SList
supporting all of the features noted above.
print(hosts.grep('ip6', prune=True).n)
# Kubernetes-managed hosts file. 127.0.0.1 localhost 10.12.9.251 jupyter-3675d82eae802db2c011037033d614a5-2dlwedcif3