xal provides an interface to run sh commands.
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 !
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...>
sh interface can be used as a factory to create
>>> 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.
Command constructor accepts strings or iterables:
>>> other_command = session.sh(['echo', '-n', 'Hello']) >>> other_command.command 'echo -n Hello'
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
>>> piped = echo.pipe(grep) >>> piped().stdout 'world\n' >>> piped = echo | grep >>> piped().stdout 'world\n'
It also works with
>>> session.sh.run(echo | grep).stdout 'world\n'
Run ShCommand, retrieve ShResult¶
Command instances are callables. When called, they return a
>>> result = command() >>> result <xal.sh.resource.ShResult object at 0x...> >>> result.stdout 'Hello' >>> result.return_code 0 >>> result.succeeded True
sh interface also has a
run() shortcut that creates
ShCommand, runs it and returns
>>> 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
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...