Fred Drake | 4fd1292 | 1997-06-12 16:05:46 +0000 | [diff] [blame] | 1 | \section{Standard module \sectcode{commands}} % If implemented in Python |
| 2 | \stmodindex{commands} |
| 3 | |
| 4 | The \code{commands} module contains wrapper functions for \code{os.popen()} |
| 5 | which take a system command as a string and return any output generated by |
| 6 | the command, and optionally, the exit status. |
| 7 | |
| 8 | The \code{commands} module is only usable on systems which support |
| 9 | \code{popen()} (currently \UNIX{}). |
| 10 | |
| 11 | The \code{commands} module defines the following functions: |
| 12 | |
| 13 | \renewcommand{\indexsubitem}{(in module commands)} |
| 14 | \begin{funcdesc}{getstatusoutput}{cmd} |
| 15 | Execute the string \var{cmd} in a shell with \code{os.popen()} and return |
| 16 | a 2-tuple (status, output). \var{cmd} is actually run as |
| 17 | \samp{cmd ; 2$>$\$1}, so that the returned output will contain output |
| 18 | or error messages. A trailing newline is stripped from the output. |
| 19 | The exit status for the command can be interpreted according to the |
| 20 | rules for the \C{} function \code{wait()}. |
| 21 | \end{funcdesc} |
| 22 | |
| 23 | \begin{funcdesc}{getoutput}{cmd} |
| 24 | Like \code{getstatusoutput()}, except the exit status is ignored and |
| 25 | the return value is a string containing the command's output. |
| 26 | \end{funcdesc} |
| 27 | |
| 28 | \begin{funcdesc}{getstatus}{file} |
| 29 | Return the output of \samp{ls -ld \var{file}} as a string. This |
| 30 | function uses the \code{getoutput()} function, and properly escapes |
| 31 | backslashes and dollar signs in the argument. |
| 32 | \end{funcdesc} |
| 33 | |
| 34 | Example: |
| 35 | |
| 36 | \begin{verbatim} |
| 37 | >>> import commands |
| 38 | >>> commands.getstatusoutput('ls /bin/ls') |
| 39 | (0, '/bin/ls') |
| 40 | >>> commands.getstatusoutput('cat /bin/junk') |
| 41 | (256, 'cat: /bin/junk: No such file or directory') |
| 42 | >>> commands.getstatusoutput('/bin/junk') |
| 43 | (256, 'sh: /bin/junk: not found') |
| 44 | >>> commands.getoutput('ls /bin/ls') |
| 45 | '/bin/ls' |
| 46 | >>> commands.getstatus('/bin/ls') |
| 47 | '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls' |
| 48 | \end{verbatim} |