blob: c96953cb9c6460a43d3abcea6cfef10993818e2f [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# Module 'commands'
2#
3# Various tools for executing commands and looking at their output and status.
4
5import rand
6import posix
Guido van Rossum5c124871990-10-21 16:14:50 +00007import stat
Guido van Rossumc6360141990-10-13 19:23:40 +00008import path
9
10
11# Get 'ls -l' status for an object into a string
12#
13def getstatus(file):
14 return getoutput('ls -ld' + mkarg(file))
15
16
17# Get the output from a shell command into a string.
18# The exit status is ignored; a trailing newline is stripped.
19# Assume the command will work with ' >tempfile 2>&1' appended.
20# XXX This should use posix.popen() instead, should it exist.
21#
22def getoutput(cmd):
23 return getstatusoutput(cmd)[1]
24
25
26# Ditto but preserving the exit status.
27# Returns a pair (sts, output)
28#
29def getstatusoutput(cmd):
30 tmp = '/usr/tmp/wdiff' + `rand.rand()`
31 sts = -1
32 try:
33 sts = posix.system(cmd + ' >' + tmp + ' 2>&1')
34 text = readfile(tmp)
35 finally:
36 altsts = posix.system('rm -f ' + tmp)
37 if text[-1:] = '\n': text = text[:-1]
38 return sts, text
39
40
41# Return a string containing a file's contents.
42#
43def readfile(fn):
Guido van Rossum5c124871990-10-21 16:14:50 +000044 return open(fn, 'r').read(posix.stat(fn)[stat.ST_SIZE])
Guido van Rossumc6360141990-10-13 19:23:40 +000045
46
47# Make command argument from directory and pathname (prefix space, add quotes).
48#
49def mk2arg(head, x):
50 return mkarg(path.cat(head, x))
51
52
53# Make a shell command argument from a string.
54# Two strategies: enclose in single quotes if it contains none;
55# otherwis, enclose in double quotes and prefix quotable characters
56# with backslash.
57#
58def mkarg(x):
59 if '\'' not in x:
60 return ' \'' + x + '\''
61 s = ' "'
62 for c in x:
63 if c in '\\$"':
64 s = s + '\\'
65 s = s + c
66 s = s + '"'
67 return s