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 |
Guido van Rossum | 5c12487 | 1990-10-21 16:14:50 +0000 | [diff] [blame] | 7 | import stat |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 8 | import path |
| 9 | |
| 10 | |
| 11 | # Get 'ls -l' status for an object into a string |
| 12 | # |
| 13 | def 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 | # |
| 22 | def getoutput(cmd): |
| 23 | return getstatusoutput(cmd)[1] |
| 24 | |
| 25 | |
| 26 | # Ditto but preserving the exit status. |
| 27 | # Returns a pair (sts, output) |
| 28 | # |
| 29 | def 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 | # |
| 43 | def readfile(fn): |
Guido van Rossum | 5c12487 | 1990-10-21 16:14:50 +0000 | [diff] [blame] | 44 | return open(fn, 'r').read(posix.stat(fn)[stat.ST_SIZE]) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 45 | |
| 46 | |
| 47 | # Make command argument from directory and pathname (prefix space, add quotes). |
| 48 | # |
| 49 | def 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 | # |
| 58 | def 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 |