| 1 |
import os, struct, marshal, sys |
| 2 |
|
| 3 |
class Exchange(object): |
| 4 |
def __init__(self, inp, out): |
| 5 |
self.out = out |
| 6 |
self.inp = inp |
| 7 |
|
| 8 |
def send(self, data): |
| 9 |
if marshal is None: |
| 10 |
return |
| 11 |
s = marshal.dumps(data) |
| 12 |
h = struct.pack('L', len(s)) |
| 13 |
self.out.write(h+s) |
| 14 |
self.out.flush() |
| 15 |
|
| 16 |
def recv(self): |
| 17 |
if not struct: |
| 18 |
return 'done' |
| 19 |
HSIZE = struct.calcsize('L') |
| 20 |
h = self.inp.read(HSIZE) |
| 21 |
if len(h) < HSIZE: |
| 22 |
raise EOFError |
| 23 |
size = struct.unpack('L', h)[0] |
| 24 |
s = self.inp.read(size) |
| 25 |
if len(s) < size: |
| 26 |
raise EOFError |
| 27 |
return marshal.loads(s) |
| 28 |
|
| 29 |
def forceclose(self): |
| 30 |
try: |
| 31 |
self.out.close() |
| 32 |
except: |
| 33 |
pass |
| 34 |
|
| 35 |
try: |
| 36 |
self.inp.close() |
| 37 |
except: |
| 38 |
pass |
| 39 |
|
| 40 |
class SlaveProcess(object): |
| 41 |
_broken = False |
| 42 |
|
| 43 |
def __init__(self, slave_impl): |
| 44 |
if sys.platform == 'win32': |
| 45 |
unbuffered = '' |
| 46 |
else: |
| 47 |
unbuffered = '-u' |
| 48 |
inp, out = os.popen2('%s %s %s' % (sys.executable, unbuffered, os.path.abspath(slave_impl))) |
| 49 |
self.exchg = Exchange(out, inp) |
| 50 |
|
| 51 |
def cmd(self, data): |
| 52 |
self.exchg.send(data) |
| 53 |
try: |
| 54 |
return self.exchg.recv() |
| 55 |
except EOFError: |
| 56 |
self._broken = True |
| 57 |
raise |
| 58 |
|
| 59 |
def close(self): |
| 60 |
if not self._broken: |
| 61 |
assert self.cmd(None) == 'done' |
| 62 |
self.exchg.forceclose() |
| 63 |
|
| 64 |
class Slave(object): |
| 65 |
|
| 66 |
def do_cmd(self, data): |
| 67 |
raise NotImplementedError |
| 68 |
|
| 69 |
def do(self): |
| 70 |
exchg = Exchange(sys.stdin, sys.stdout) |
| 71 |
while True: |
| 72 |
try: |
| 73 |
cmd = exchg.recv() |
| 74 |
except EOFError: |
| 75 |
break |
| 76 |
if cmd is None: |
| 77 |
exchg.send('done') |
| 78 |
break |
| 79 |
result = self.do_cmd(cmd) |
| 80 |
exchg.send(result) |