blob: c3f771085e0193d318a76d7cf1e698537938276f [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
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
11The :mod:`commands` module contains wrapper functions for :func:`os.popen` which
12take a system command as a string and return any output generated by the command
13and, optionally, the exit status.
14
15The :mod:`subprocess` module provides more powerful facilities for spawning new
16processes and retrieving their results. Using the :mod:`subprocess` module is
17preferable to using the :mod:`commands` module.
18
19The :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
37.. function:: getstatus(file)
38
39 Return the output of ``ls -ld file`` as a string. This function uses the
40 :func:`getoutput` function, and properly escapes backslashes and dollar signs in
41 the argument.
42
43 .. deprecated:: 2.6
44 This function is nonobvious and useless, also the name is misleading in the
Benjamin Peterson3aa84a72008-05-26 19:41:53 +000045 presence of :func:`getstatusoutput`. It is removed in 3.x.
46
47.. warning::
48
49 Two undocumented functions in this module, :func:`mk2arg` and :func:`mkargs`
50 are removed in 3.x.
51
Georg Brandl8ec7f652007-08-15 14:28:01 +000052
53Example::
54
55 >>> import commands
56 >>> commands.getstatusoutput('ls /bin/ls')
57 (0, '/bin/ls')
58 >>> commands.getstatusoutput('cat /bin/junk')
59 (256, 'cat: /bin/junk: No such file or directory')
60 >>> commands.getstatusoutput('/bin/junk')
61 (256, 'sh: /bin/junk: not found')
62 >>> commands.getoutput('ls /bin/ls')
63 '/bin/ls'
64 >>> commands.getstatus('/bin/ls')
65 '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
66
67
68.. seealso::
69
70 Module :mod:`subprocess`
71 Module for spawning and managing subprocesses.
72