blob: dc467408310c1787c7e41cbde1f24fa2daf842d8 [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 Rossumf49ef1c1990-10-24 16:40:15 +000044 st = posix.stat(fn)
45 size = st[stat.ST_SIZE]
46 if not size: return ''
47 try:
48 fp = open(fn, 'r')
49 except:
50 raise posix.error, 'readfile(' + fn + '): open failed'
51 try:
52 return fp.read(size)
53 except:
54 raise posix.error, 'readfile(' + fn + '): read failed'
Guido van Rossumc6360141990-10-13 19:23:40 +000055
56
57# Make command argument from directory and pathname (prefix space, add quotes).
58#
59def mk2arg(head, x):
60 return mkarg(path.cat(head, x))
61
62
63# Make a shell command argument from a string.
64# Two strategies: enclose in single quotes if it contains none;
65# otherwis, enclose in double quotes and prefix quotable characters
66# with backslash.
67#
68def mkarg(x):
69 if '\'' not in x:
70 return ' \'' + x + '\''
71 s = ' "'
72 for c in x:
73 if c in '\\$"':
74 s = s + '\\'
75 s = s + c
76 s = s + '"'
77 return s