1: #line 6 "commands.ipk"
2: """Execute shell commands via os.popen() and return status, output.
3:
4: Interface summary:
5:
6: import commands
7:
8: outtext = commands.getoutput(cmd)
9: (exitstatus, outtext) = commands.getstatusoutput(cmd)
10: outtext = commands.getstatus(file) # returns output of "ls -ld file"
11:
12: A trailing newline is removed from the output string.
13:
14: Encapsulates the basic operation:
15:
16: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
17: text = pipe.read()
18: sts = pipe.close()
19:
20: [Note: it would be nice to add functions to interpret the exit status.]
21: """
22:
23:
24:
25:
26:
27: def getoutput(cmd):
28: """Return output (stdout or stderr) of executing cmd in a shell."""
29: return getstatusoutput(cmd)[1]
30:
31:
32:
33:
34:
35: def getstatusoutput(cmd):
36: """Return (status, output) of executing cmd in a shell."""
37: import os
38: import sys
39: if sys.platform == 'Win32':
40: pipe = os.popen(cmd, 'r')
41: else:
42: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
43: text = pipe.read()
44: sts = pipe.close()
45: if sts == None: sts = 0
46: if text[-1:] == '\n': text = text[:-1]
47: return sts, text
48:
49:
50:
51:
52: def mk2arg(head, x):
53: import os
54: return mkarg(os.path.join(head, x))
55:
56:
57:
58:
59:
60:
61:
62:
63:
64: def mkarg(x):
65: if '\'' not in x:
66: return ' \'' + x + '\''
67: s = ' "'
68: for c in x:
69: if c in '\\$"`':
70: s = s + '\\'
71: s = s + c
72: s = s + '"'
73: return s