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. |
Guido van Rossum | e58f98b | 1992-03-31 19:02:55 +0000 | [diff] [blame^] | 4 | # |
| 5 | # NB This only works (and is only relevant) for UNIX. |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 7 | |
| 8 | # Get 'ls -l' status for an object into a string |
| 9 | # |
| 10 | def getstatus(file): |
| 11 | return getoutput('ls -ld' + mkarg(file)) |
| 12 | |
| 13 | |
| 14 | # Get the output from a shell command into a string. |
| 15 | # The exit status is ignored; a trailing newline is stripped. |
Guido van Rossum | 48154be | 1991-08-16 13:23:29 +0000 | [diff] [blame] | 16 | # Assume the command will work with '{ ... ; } 2>&1' around it.. |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 17 | # |
| 18 | def getoutput(cmd): |
| 19 | return getstatusoutput(cmd)[1] |
| 20 | |
| 21 | |
| 22 | # Ditto but preserving the exit status. |
| 23 | # Returns a pair (sts, output) |
| 24 | # |
| 25 | def getstatusoutput(cmd): |
Guido van Rossum | 48154be | 1991-08-16 13:23:29 +0000 | [diff] [blame] | 26 | import posix |
| 27 | pipe = posix.popen('{ ' + cmd + '; } 2>&1', 'r') |
| 28 | text = pipe.read() |
| 29 | sts = pipe.close() |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 30 | if sts == None: sts = 0 |
| 31 | if text[-1:] == '\n': text = text[:-1] |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 32 | return sts, text |
| 33 | |
| 34 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 35 | # Make command argument from directory and pathname (prefix space, add quotes). |
| 36 | # |
| 37 | def mk2arg(head, x): |
Guido van Rossum | e58f98b | 1992-03-31 19:02:55 +0000 | [diff] [blame^] | 38 | import posixpath |
| 39 | return mkarg(posixpath.join(head, x)) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 40 | |
| 41 | |
| 42 | # Make a shell command argument from a string. |
| 43 | # Two strategies: enclose in single quotes if it contains none; |
Guido van Rossum | 48154be | 1991-08-16 13:23:29 +0000 | [diff] [blame] | 44 | # otherwise, enclose in double quotes and prefix quotable characters |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 45 | # with backslash. |
| 46 | # |
| 47 | def mkarg(x): |
| 48 | if '\'' not in x: |
| 49 | return ' \'' + x + '\'' |
| 50 | s = ' "' |
| 51 | for c in x: |
| 52 | if c in '\\$"': |
| 53 | s = s + '\\' |
| 54 | s = s + c |
| 55 | s = s + '"' |
| 56 | return s |