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