blob: 84ef257a37f5e99ad6950b70d58333f5b6f7ccbd [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
Benjamin Peterson9171bed2008-05-26 20:41:45 +000019.. warning::
20
21 In 3.x, :func:`getstatus` and two undocumented functions (:func:`mk2arg` and
22 :func:`mkarg`) have been removed. Also, :func:`getstatusoutput` and
23 :func:`getoutput` have been moved to the :mod:`subprocess` module.
24
Georg Brandl8ec7f652007-08-15 14:28:01 +000025The :mod:`commands` module defines the following functions:
26
27
28.. function:: getstatusoutput(cmd)
29
30 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
31 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
32 returned output will contain output or error messages. A trailing newline is
33 stripped from the output. The exit status for the command can be interpreted
34 according to the rules for the C function :cfunc:`wait`.
35
36
37.. function:: getoutput(cmd)
38
39 Like :func:`getstatusoutput`, except the exit status is ignored and the return
40 value is a string containing the command's output.
41
42
43.. function:: getstatus(file)
44
45 Return the output of ``ls -ld file`` as a string. This function uses the
46 :func:`getoutput` function, and properly escapes backslashes and dollar signs in
47 the argument.
48
49 .. deprecated:: 2.6
Andrew M. Kuchlingf839b662008-06-20 23:14:32 +000050 This function is nonobvious and useless. The name is also misleading in the
Benjamin Peterson9171bed2008-05-26 20:41:45 +000051 presence of :func:`getstatusoutput`.
Benjamin Peterson3aa84a72008-05-26 19:41:53 +000052
Georg Brandl8ec7f652007-08-15 14:28:01 +000053
54Example::
55
56 >>> import commands
57 >>> commands.getstatusoutput('ls /bin/ls')
58 (0, '/bin/ls')
59 >>> commands.getstatusoutput('cat /bin/junk')
60 (256, 'cat: /bin/junk: No such file or directory')
61 >>> commands.getstatusoutput('/bin/junk')
62 (256, 'sh: /bin/junk: not found')
63 >>> commands.getoutput('ls /bin/ls')
64 '/bin/ls'
65 >>> commands.getstatus('/bin/ls')
66 '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
67
68
69.. seealso::
70
71 Module :mod:`subprocess`
72 Module for spawning and managing subprocesses.
73