ยปCore Development>Code coverage>Lib/commands.py

Python code coverage for Lib/commands.py

#countcontent
1n/a"""Execute shell commands via os.popen() and return status, output.
2n/a
3n/aInterface summary:
4n/a
5n/a import commands
6n/a
7n/a outtext = commands.getoutput(cmd)
8n/a (exitstatus, outtext) = commands.getstatusoutput(cmd)
9n/a outtext = commands.getstatus(file) # returns output of "ls -ld file"
10n/a
11n/aA trailing newline is removed from the output string.
12n/a
13n/aEncapsulates the basic operation:
14n/a
15n/a pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
16n/a text = pipe.read()
17n/a sts = pipe.close()
18n/a
19n/a [Note: it would be nice to add functions to interpret the exit status.]
201"""
211from warnings import warnpy3k
221warnpy3k("the commands module has been removed in Python 3.0; "
231 "use the subprocess module instead", stacklevel=2)
241del warnpy3k
25n/a
261__all__ = ["getstatusoutput","getoutput","getstatus"]
27n/a
28n/a# Module 'commands'
29n/a#
30n/a# Various tools for executing commands and looking at their output and status.
31n/a#
32n/a# NB This only works (and is only relevant) for UNIX.
33n/a
34n/a
35n/a# Get 'ls -l' status for an object into a string
36n/a#
371def getstatus(file):
38n/a """Return output of "ls -ld <file>" in a string."""
391 import warnings
401 warnings.warn("commands.getstatus() is deprecated", DeprecationWarning, 2)
411 return getoutput('ls -ld' + mkarg(file))
42n/a
43n/a
44n/a# Get the output from a shell command into a string.
45n/a# The exit status is ignored; a trailing newline is stripped.
46n/a# Assume the command will work with '{ ... ; } 2>&1' around it..
47n/a#
481def getoutput(cmd):
49n/a """Return output (stdout or stderr) of executing cmd in a shell."""
502 return getstatusoutput(cmd)[1]
51n/a
52n/a
53n/a# Ditto but preserving the exit status.
54n/a# Returns a pair (sts, output)
55n/a#
561def getstatusoutput(cmd):
57n/a """Return (status, output) of executing cmd in a shell."""
584 import os
594 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
604 text = pipe.read()
614 sts = pipe.close()
624 if sts is None: sts = 0
634 if text[-1:] == '\n': text = text[:-1]
644 return sts, text
65n/a
66n/a
67n/a# Make command argument from directory and pathname (prefix space, add quotes).
68n/a#
691def mk2arg(head, x):
700 import os
710 return mkarg(os.path.join(head, x))
72n/a
73n/a
74n/a# Make a shell command argument from a string.
75n/a# Return a string beginning with a space followed by a shell-quoted
76n/a# version of the argument.
77n/a# Two strategies: enclose in single quotes if it contains none;
78n/a# otherwise, enclose in double quotes and prefix quotable characters
79n/a# with backslash.
80n/a#
811def mkarg(x):
821 if '\'' not in x:
831 return ' \'' + x + '\''
840 s = ' "'
850 for c in x:
860 if c in '\\$"`':
870 s = s + '\\'
880 s = s + c
890 s = s + '"'
900 return s