Using Execute

Execute provides handy functions for several patterns of sub-process execution. Each of these patterns is described below.

Simple

The simple() function provides a simple way to run an executable in a sub-process that requires no input and where you’d like the output of both the standard and error output streams combined and returned in one string.

For example, suppose you needed to execute the following python script in a sub-process:

import sys
print sys.argv[1:]
sys.stdout.flush()
sys.stderr.write('An error occurred!\n')

As an aside, it’s unlikely you’d want to do this. It’s much more likely that you’d want to use simple() to run something that wasn’t written in python.

However, if python contained the path to the python executable you’d want to use to run the above script, and path contained the path to the script on disk, you could use simple() to run it and capture the output as follows:

>>> from execute import simple
>>> output = simple(' '.join((python,path,'x=1 --y=2 a b')))

You now have the output in a string and you can do whatever you like with it:

>>> print output
['x=1', '--y=2', 'a', 'b']
An error occurred!
<BLANKLINE>

Return Code

The returncode() function provides a simple way to get the return code set by the command executed. The command is run in a sub-process and must require no input.

For example, suppose you needed to get the return code set by the following python script:

import sys
sys.exit(4)

If python contained the path to the python executable you’d want to use to run the above script, and path contained the path to the script on disk, you could use returncode() to obtain the return code as follows:

>>> from execute import returncode
>>> code = returncode(python+' '+path)

You now have the return code and can do whatever you like with it:

>>> print code
4

Both

The both() function provides a simple way to get the output and return code of the command executed. The command is run in a sub-process and must require no input. The output of both the standard and error output streams will be combined and returned in one string.

For example, suppose you needed to execute the following python script in a sub-process, want its output and want to know if it succeeded by way of its return code:

import sys
print sys.argv[1:]
sys.stdout.flush()
sys.stderr.write('An error occurred!\n')
sys.exit(13)

If python contained the path to the python executable you’d want to use to run the above script, and path contained the path to the script on disk, you could use both() to run it, capturing the output and the return code as follows:

>>> from execute import both
>>> output, returncode = both(' '.join((python,path,'x=1 --y=2 a b')))

You can now do whatever you like with either the output or the return code:

>>> print output
['x=1', '--y=2', 'a', 'b']
An error occurred!
<BLANKLINE>
>>> print returncode
13

Table Of Contents

Previous topic

Installation Instructions

Next topic

API Reference

This Page