blob: 4d16eefaa4bc55d9c06bc153a4ce0e094bac0d60 [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.
4
Guido van Rossumc6360141990-10-13 19:23:40 +00005
6# Get 'ls -l' status for an object into a string
7#
8def 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 Rossum48154be1991-08-16 13:23:29 +000014# Assume the command will work with '{ ... ; } 2>&1' around it..
Guido van Rossumc6360141990-10-13 19:23:40 +000015#
16def getoutput(cmd):
17 return getstatusoutput(cmd)[1]
18
19
20# Ditto but preserving the exit status.
21# Returns a pair (sts, output)
22#
23def getstatusoutput(cmd):
Guido van Rossum48154be1991-08-16 13:23:29 +000024 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 Rossumc6360141990-10-13 19:23:40 +000029 if text[-1:] = '\n': text = text[:-1]
30 return sts, text
31
32
Guido van Rossumc6360141990-10-13 19:23:40 +000033# Make command argument from directory and pathname (prefix space, add quotes).
34#
35def mk2arg(head, x):
Guido van Rossum48154be1991-08-16 13:23:29 +000036 import path
37 return mkarg(path.join(head, x))
Guido van Rossumc6360141990-10-13 19:23:40 +000038
39
40# Make a shell command argument from a string.
41# Two strategies: enclose in single quotes if it contains none;
Guido van Rossum48154be1991-08-16 13:23:29 +000042# otherwise, enclose in double quotes and prefix quotable characters
Guido van Rossumc6360141990-10-13 19:23:40 +000043# with backslash.
44#
45def 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