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