blob: 6471a8db594c29e1df79dbce42b3b26355be54d9 [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.
Guido van Rossume58f98b1992-03-31 19:02:55 +00004#
5# NB This only works (and is only relevant) for UNIX.
Guido van Rossumc6360141990-10-13 19:23:40 +00006
Guido van Rossumc6360141990-10-13 19:23:40 +00007
8# Get 'ls -l' status for an object into a string
9#
10def 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 Rossum48154be1991-08-16 13:23:29 +000016# Assume the command will work with '{ ... ; } 2>&1' around it..
Guido van Rossumc6360141990-10-13 19:23:40 +000017#
18def getoutput(cmd):
19 return getstatusoutput(cmd)[1]
20
21
22# Ditto but preserving the exit status.
23# Returns a pair (sts, output)
24#
25def getstatusoutput(cmd):
Guido van Rossume65cce51993-11-08 15:05:21 +000026 import os
27 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
Guido van Rossum48154be1991-08-16 13:23:29 +000028 text = pipe.read()
29 sts = pipe.close()
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000030 if sts == None: sts = 0
31 if text[-1:] == '\n': text = text[:-1]
Guido van Rossumc6360141990-10-13 19:23:40 +000032 return sts, text
33
34
Guido van Rossumc6360141990-10-13 19:23:40 +000035# Make command argument from directory and pathname (prefix space, add quotes).
36#
37def mk2arg(head, x):
Guido van Rossume65cce51993-11-08 15:05:21 +000038 import os
39 return mkarg(os.path.join(head, x))
Guido van Rossumc6360141990-10-13 19:23:40 +000040
41
42# Make a shell command argument from a string.
Guido van Rossume1130a41995-01-04 19:20:00 +000043# Return a string beginning with a space followed by a shell-quoted
44# version of the argument.
Guido van Rossumc6360141990-10-13 19:23:40 +000045# Two strategies: enclose in single quotes if it contains none;
Guido van Rossum48154be1991-08-16 13:23:29 +000046# otherwise, enclose in double quotes and prefix quotable characters
Guido van Rossumc6360141990-10-13 19:23:40 +000047# with backslash.
48#
49def mkarg(x):
50 if '\'' not in x:
51 return ' \'' + x + '\''
52 s = ' "'
53 for c in x:
Guido van Rossum01ca3361992-07-13 14:28:59 +000054 if c in '\\$"`':
Guido van Rossumc6360141990-10-13 19:23:40 +000055 s = s + '\\'
56 s = s + c
57 s = s + '"'
58 return s