Skip to main content

External Command - subprocess with advanced output processing

Project description

extcmd - subprocess with advanced output processing

This rather elaborate example shows a few interesting features of the library. Each line of the called command is passed to a Chain delegate, there are three copies made, the two first are just passed to another delegate while the last is modified with a Transform delegate. Finally all copies end up in our sink which is a composition of a simple Transform that prepends the stream name and a Redirect that, by default, just writes each line back to the corresponding stream.

Everything is encapsulated in a single module, extcmd:

>>> import extcmd
>>> import re

Create our sink object, it will simply write stuff back to the right stream while prepending the stream name to each line for easy inspection (and fun):

>>> sink = extcmd.Transform(lambda stream_name, line: "{0}: {1}".format(stream_name, line),
...                         extcmd.Redirect())
>>> better_subprocess = extcmd.ExternalCommandWithDelegate(
...     extcmd.Chain([
...         sink,  # pass one copy directly to the sink
...         sink,  # pass second copy directly to the sink
...         # transform a third copy with regular expression
...         extcmd.Transform(lambda stream_name, line: re.sub("hello", "bye", line, flags=re.I), sink),
...     ])
... )

After constructing that chain we can just call commands. As in subprocess there is also check_call() which raises an exception on failure:

>>> returncode = better_subprocess.call(['echo', 'Hello World'])
stdout: Hello World
stdout: Hello World
stdout: bye World

You can still look at returncode, it is returned from each call():

>>> returncode
0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
extcmd-1.0b1.tar.gz (4.1 kB) Copy SHA256 hash SHA256 Source None Feb 2, 2012

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page