| 1 |
import exceptions, os |
| 2 |
from pypy.tool import slaveproc |
| 3 |
|
| 4 |
class IsolateException(Exception): |
| 5 |
pass |
| 6 |
|
| 7 |
class IsolateInvoker(object): |
| 8 |
|
| 9 |
|
| 10 |
def __init__(self, isolate, name): |
| 11 |
self.isolate = isolate |
| 12 |
self.name = name |
| 13 |
|
| 14 |
def __call__(self, *args): |
| 15 |
return self.isolate._invoke(self.name, args) |
| 16 |
|
| 17 |
def __repr__(self): |
| 18 |
return "<invoker for %r . %r>" % (self.isolate.module, self.name) |
| 19 |
|
| 20 |
def close_isolate(self): |
| 21 |
self.isolate._close() |
| 22 |
|
| 23 |
class Isolate(object): |
| 24 |
""" |
| 25 |
Isolate lets load a module in a different process, |
| 26 |
and support invoking functions from it passing and |
| 27 |
returning simple values |
| 28 |
|
| 29 |
module: a dotted module name or a tuple (directory, module-name) |
| 30 |
""" |
| 31 |
_closed = False |
| 32 |
|
| 33 |
def __init__(self, module): |
| 34 |
self.module = module |
| 35 |
self.slave = slaveproc.SlaveProcess(os.path.join(os.path.dirname(__file__), |
| 36 |
'isolate_slave.py')) |
| 37 |
res = self.slave.cmd(('load', module)) |
| 38 |
assert res == 'loaded' |
| 39 |
|
| 40 |
def __getattr__(self, name): |
| 41 |
return IsolateInvoker(self, name) |
| 42 |
|
| 43 |
def _invoke(self, func, args): |
| 44 |
status, value = self.slave.cmd(('invoke', (func, args))) |
| 45 |
print 'OK' |
| 46 |
if status == 'ok': |
| 47 |
return value |
| 48 |
else: |
| 49 |
exc_type_module, exc_type_name = value |
| 50 |
if exc_type_module == 'exceptions': |
| 51 |
raise getattr(exceptions, exc_type_name) |
| 52 |
else: |
| 53 |
raise IsolateException("%s.%s" % value) |
| 54 |
|
| 55 |
def _close(self): |
| 56 |
if not self._closed: |
| 57 |
self.slave.close() |
| 58 |
self._closed = True |
| 59 |
|
| 60 |
def __del__(self): |
| 61 |
self._close() |
| 62 |
|
| 63 |
def close_isolate(isolate): |
| 64 |
assert isinstance(isolate, Isolate) |
| 65 |
isolate._close() |