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