Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`commands` --- Utilities for running commands |
| 3 | ================================================== |
| 4 | |
| 5 | .. module:: commands |
| 6 | :platform: Unix |
| 7 | :synopsis: Utility functions for running external commands. |
| 8 | .. sectionauthor:: Sue Williams <sbw@provis.com> |
| 9 | |
| 10 | |
| 11 | The :mod:`commands` module contains wrapper functions for :func:`os.popen` which |
| 12 | take a system command as a string and return any output generated by the command |
| 13 | and, optionally, the exit status. |
| 14 | |
| 15 | The :mod:`subprocess` module provides more powerful facilities for spawning new |
| 16 | processes and retrieving their results. Using the :mod:`subprocess` module is |
| 17 | preferable to using the :mod:`commands` module. |
| 18 | |
| 19 | The :mod:`commands` module defines the following functions: |
| 20 | |
| 21 | |
| 22 | .. function:: getstatusoutput(cmd) |
| 23 | |
| 24 | Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple |
| 25 | ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the |
| 26 | returned output will contain output or error messages. A trailing newline is |
| 27 | stripped from the output. The exit status for the command can be interpreted |
| 28 | according to the rules for the C function :cfunc:`wait`. |
| 29 | |
| 30 | |
| 31 | .. function:: getoutput(cmd) |
| 32 | |
| 33 | Like :func:`getstatusoutput`, except the exit status is ignored and the return |
| 34 | value is a string containing the command's output. |
| 35 | |
| 36 | Example:: |
| 37 | |
| 38 | >>> import commands |
| 39 | >>> commands.getstatusoutput('ls /bin/ls') |
| 40 | (0, '/bin/ls') |
| 41 | >>> commands.getstatusoutput('cat /bin/junk') |
| 42 | (256, 'cat: /bin/junk: No such file or directory') |
| 43 | >>> commands.getstatusoutput('/bin/junk') |
| 44 | (256, 'sh: /bin/junk: not found') |
| 45 | >>> commands.getoutput('ls /bin/ls') |
| 46 | '/bin/ls' |
| 47 | |
| 48 | |
| 49 | .. seealso:: |
| 50 | |
| 51 | Module :mod:`subprocess` |
| 52 | Module for spawning and managing subprocesses. |
| 53 | |