Vega strike Python Modules doc
0.5.1
Documentation of the " Modules " folder of Vega strike
Main Page
Namespaces
Data Structures
Files
File List
All
Data Structures
Namespaces
Files
Functions
Variables
commands.py
Go to the documentation of this file.
1
"""Execute shell commands via os.popen() and return status, output.
2
3
Interface summary:
4
5
import commands
6
7
outtext = commands.getoutput(cmd)
8
(exitstatus, outtext) = commands.getstatusoutput(cmd)
9
outtext = commands.getstatus(file) # returns output of "ls -ld file"
10
11
A trailing newline is removed from the output string.
12
13
Encapsulates the basic operation:
14
15
pipe = os.popen('{ ' + cmd + '; } 2>&1', '
r')
16
text = pipe.read()
17
sts = pipe.close()
18
19
[Note: it would be nice to add functions to interpret the exit status.]
20
"""
21
22
__all__ = ["getstatusoutput","getoutput","getstatus"]
23
24
# Module 'commands'
25
#
26
# Various tools for executing commands and looking at their output and status.
27
#
28
# NB This only works (and is only relevant) for UNIX.
29
30
31
# Get 'ls -l' status for an object into a string
32
#
33
def getstatus(file):
34
"""
Return output of
"ls -ld <file>"
in
a string.
"""
35
return getoutput('ls -ld' + mkarg(file))
36
37
38
# Get the output from a shell command into a string.
39
# The exit status is ignored; a trailing newline is stripped.
40
# Assume the command will work with '{ ... ; } 2>&1' around it..
41
#
42
def getoutput(cmd):
43
"""
Return output (stdout
or
stderr) of executing cmd
in
a shell.
"""
44
return getstatusoutput(cmd)[1]
45
46
47
# Ditto but preserving the exit status.
48
# Returns a pair (sts, output)
49
#
50
def getstatusoutput(cmd):
51
"""
Return (status, output) of executing cmd
in
a shell.
"""
52
import os
53
pipe = os.popen('{ ' + cmd + '; } 2>&1', '
r')
54
text = pipe.read()
55
sts = pipe.close()
56
if
sts
is
None
: sts = 0
57
if
text[-1:] ==
'\n'
: text = text[:-1]
58
return
sts, text
59
60
61
# Make command argument from directory and pathname (prefix space, add quotes).
62
#
63
def
mk2arg
(head, x):
64
import
os
65
return
mkarg
(os.path.join(head, x))
66
67
68
# Make a shell command argument from a string.
69
# Return a string beginning with a space followed by a shell-quoted
70
# version of the argument.
71
# Two strategies: enclose in single quotes if it contains none;
72
# otherwise, enclose in double quotes and prefix quotable characters
73
# with backslash.
74
#
75
def
mkarg
(x):
76
if
'\''
not
in
x:
77
return
' \''
+ x +
'\''
78
s =
' "'
79
for
c
in
x:
80
if
c
in
'\\$"`'
:
81
s = s +
'\\'
82
s = s + c
83
s = s +
'"'
84
return
s
builtin
commands.py
Generated on Mon Feb 17 2014 12:38:41 for Vega strike Python Modules doc by
1.8.4