Chut’s basics

About imports

You can import chut and use commands:

>>> import chut as sh

You can import sudo:

>>> from chut import sudo

But you can also import some specific commands:

>>> from chut import cat, grep, gzip, gunzip
>>> from chut.sudo import ifconfig

Or import “all” commands. Where “all” is a unexaustive set of commands:

>>> from chut import *  

See Imports


The cd command use python os.chdir()

Some commands do not use a pipe by default. This mean that they are executed immediately. See Imports

By default a command is piped. But you can avoid this:


By default a command do not use a shell. But if you need you can use one:




You can define some aliases:

>>> sh.aliases['ll'] = '/usr/local/bin/ls -l'
>>> sh.aliases['python'] = '/opt/python3/bin/python3'
>>> print(repr(sh.ll('.')))
'/usr/local/bin/ls -l .'
>>> print(repr(sh.python('-c "import sys"')))
"/opt/python3/bin/python3 -c 'import sys'"


Chut use a copy of os.environ but you can modify values:

>>> from chut import env
>>> env.path = '/usr/bin:/usr/local/bin'
>>> env.path
['/usr/bin', '/usr/local/bin']
>>> env.path = ['/usr/bin', '/usr/local/bin']
>>> env.path
['/usr/bin', '/usr/local/bin']
>>> env.path += ['bin']
>>> env.path
['/usr/bin', '/usr/local/bin', 'bin']

Only path return a list. Other values return a string.

You can also pass a copy to your commands:

>>> env = sh.env.copy()
>>>'-', env=env)
'cat -'

The environment can also be temporarily modified with a “with” statement. In this example, “HOME” is modified only inside the “with” block and restored at the end:

>>> with sh.env(HOME="/home/foo"):
...     str(sh.echo("$HOME", sh=True))

The test command

You can use the test command:

>>> from chut import test

>>> # test -f chut/
>>> bool(test.f('chut/'))

>>> # test -x chut/
>>> if test.x('chut/'):
...     print('chut/ is executable')


Chut provide logging facility:

>>> import sys
>>> log = sh.logopts(fmt='brief', stream=sys.stdout)
>>>'info message')

When logging is configured you can use those simple functions:

>>> from chut import debug, info, error
>>> info('info message')
>>> debug('debug message')
>>> error('error message')

Notice that if you use %options in a console_script docstring then you don’t need to use logopts. The decorator will do the job for you.

Run a large amount of processes

You can use the method to run a large amount of commands with the same binary. Arguments must be a list of string or list:

>>> results =['.', ['-l', '.']])
>>> [res.succeeded for res in results]
[True, True]


You can print your pipe:

>>> print(repr(cat('README.txt') | grep('Chut')))
'cat README.txt | grep Chut'

You can also activate logging:

>>> sh.set_debug()
>>> print(cat('README.rst') | grep('Chut') | sh.head('-n1')) 
Popen(['cat', 'README.rst'], **{...})
Popen(['grep', 'Chut'], **{...})
Popen(['head', '-n1'], **{...})