sh commands

xal provides an interface to run sh commands.

Note

xal doesn’t pretend to be the best library to run sh commands. At the moment, it focuses on providing a single API to execute sh commands in various situations, such as on local machine or remote machine. If you like the concept and want more features, let’s join the project [1]!

Use sh interface

Let’s consider a xal session:

>>> import xal
>>> session = xal.LocalSession()

Sh API is registered as sh in xal‘s builtin Sessions:

>>> session.sh  
<xal.sh.local.LocalShProvider object at 0x...>

Setup ShCommand

The sh interface can be used as a factory to create ShCommand resources:

>>> command = session.sh('echo -n Hello')
>>> command
ShCommand(echo -n Hello)
>>> print command
echo -n Hello

Command resources just describe commands. They are not executed automatically once created. They are not representing processes. Remember them as commands you prepare (arguments, stdout, stdin, stderr, pipes, ...) before you run them.

Arguments

Command constructor accepts strings or iterables:

>>> other_command = session.sh(['echo', '-n', 'Hello'])
>>> other_command.command
'echo -n Hello'

Pipes

You can create and handle pipes, they are commands too.

Let’s consider two commands:

>>> echo = session.sh("echo -ne 'hello\nworld'")
>>> grep = session.sh("grep 'world'")

We can chain them using pipe() method or pipe operator:

>>> piped = echo.pipe(grep)
>>> piped().stdout
'world\n'

>>> piped = echo | grep
>>> piped().stdout
'world\n'

It also works with run() shortcut:

>>> session.sh.run(echo | grep).stdout
'world\n'

Run ShCommand, retrieve ShResult

Command instances are callables. When called, they return a ShResult instance:

>>> result = command()
>>> result  
<xal.sh.resource.ShResult object at 0x...>
>>> result.stdout
'Hello'
>>> result.return_code
0
>>> result.succeeded
True

The sh interface also has a run() shortcut that creates ShCommand, runs it and returns ShResult:

>>> session.sh.run('echo -n Hello').stdout
'Hello'

Differences with subprocess

xal‘s sh interface is made to run sh commands in a session. Think of the commands always run with sh -c. Whereas Python’s subprocess sets shell=False by default.

This postulate influences design. XAL’s sh interface helps you create and run commands through sh: pipes, redirects...

References

[1]https://github.com/benoitbryon/xal/issues