-
Notifications
You must be signed in to change notification settings - Fork 2
/
spawn.py
109 lines (75 loc) · 2.09 KB
/
spawn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# -*- Python -*-
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
import journal
info = journal.info( 'spawn' )
def spawn(command, dry_run = 0, env = None):
"""
command: command to run
env: environment variables to pass to the process in which the command will be executed
dry_run: if true, only print the command to be excuted
return: fail(bool), out(str), error(str)
"""
if type(command) == list:
cmd = ' '.join(command)
else:
assert(type(command) == types.StringType)
cmd = command
pass
if dry_run:
info.log( "Command to execute: \n%s" % cmd )
return
info.log( "Executing: \n%s" % cmd )
import subprocess
log = OStrStream()
errlog = OStrStream()
p = subprocess.Popen(
cmd, stdout = log, stderr = errlog, shell = True, env = env)
ret = p.wait()
del p
info.log( "cmd \n%s\n finished" % cmd )
return ret, log.str(), errlog.str()
import types
class OStrStream:
def __init__(self):
import tempfile
f = self.__filepath__ = tempfile.mktemp()
self.__stream__ = open( f, 'w' )
return
def __del__(self):
del self.__stream__
import os
os.remove( self.__filepath__ )
return
def __getattr__(self, name):
return getattr(self.__stream__, name)
def str(self):
self.__stream__.close()
s = open(self.__filepath__).read()
return s
pass # end of OStrStream
def test_spawn( ):
print spawn( 'ls' )
return
def test_OStrStream():
oss = OStrStream()
print >> oss, "hello"
assert oss.str() == 'hello\n'
return
def test():
test_OStrStream()
test_spawn()
return
if __name__ == '__main__': test()
# version
__id__ = "$Id$"
# End of file