| 1 |
from multiprocessing import freeze_support |
| 2 |
from multiprocessing.managers import BaseManager, BaseProxy |
| 3 |
import operator |
| 4 |
|
| 5 |
## |
| 6 |
|
| 7 |
class Foo: |
| 8 |
def f(self): |
| 9 |
print('you called Foo.f()') |
| 10 |
def g(self): |
| 11 |
print('you called Foo.g()') |
| 12 |
def _h(self): |
| 13 |
print('you called Foo._h()') |
| 14 |
|
| 15 |
# A simple generator function |
| 16 |
def baz(): |
| 17 |
for i in range(10): |
| 18 |
yield i*i |
| 19 |
|
| 20 |
# Proxy type for generator objects |
| 21 |
class GeneratorProxy(BaseProxy): |
| 22 |
_exposed_ = ['__next__'] |
| 23 |
def __iter__(self): |
| 24 |
return self |
| 25 |
def __next__(self): |
| 26 |
return self._callmethod('__next__') |
| 27 |
|
| 28 |
# Function to return the operator module |
| 29 |
def get_operator_module(): |
| 30 |
return operator |
| 31 |
|
| 32 |
## |
| 33 |
|
| 34 |
class MyManager(BaseManager): |
| 35 |
pass |
| 36 |
|
| 37 |
# register the Foo class; make `f()` and `g()` accessible via proxy |
| 38 |
MyManager.register('Foo1', Foo) |
| 39 |
|
| 40 |
# register the Foo class; make `g()` and `_h()` accessible via proxy |
| 41 |
MyManager.register('Foo2', Foo, exposed=('g', '_h')) |
| 42 |
|
| 43 |
# register the generator function baz; use `GeneratorProxy` to make proxies |
| 44 |
MyManager.register('baz', baz, proxytype=GeneratorProxy) |
| 45 |
|
| 46 |
# register get_operator_module(); make public functions accessible via proxy |
| 47 |
MyManager.register('operator', get_operator_module) |
| 48 |
|
| 49 |
## |
| 50 |
|
| 51 |
def test(): |
| 52 |
manager = MyManager() |
| 53 |
manager.start() |
| 54 |
|
| 55 |
print('-' * 20) |
| 56 |
|
| 57 |
f1 = manager.Foo1() |
| 58 |
f1.f() |
| 59 |
f1.g() |
| 60 |
assert not hasattr(f1, '_h') |
| 61 |
assert sorted(f1._exposed_) == sorted(['f', 'g']) |
| 62 |
|
| 63 |
print('-' * 20) |
| 64 |
|
| 65 |
f2 = manager.Foo2() |
| 66 |
f2.g() |
| 67 |
f2._h() |
| 68 |
assert not hasattr(f2, 'f') |
| 69 |
assert sorted(f2._exposed_) == sorted(['g', '_h']) |
| 70 |
|
| 71 |
print('-' * 20) |
| 72 |
|
| 73 |
it = manager.baz() |
| 74 |
for i in it: |
| 75 |
print('<%d>' % i, end=' ') |
| 76 |
print() |
| 77 |
|
| 78 |
print('-' * 20) |
| 79 |
|
| 80 |
op = manager.operator() |
| 81 |
print('op.add(23, 45) =', op.add(23, 45)) |
| 82 |
print('op.pow(2, 94) =', op.pow(2, 94)) |
| 83 |
print('op._exposed_ =', op._exposed_) |
| 84 |
|
| 85 |
## |
| 86 |
|
| 87 |
if __name__ == '__main__': |
| 88 |
freeze_support() |
| 89 |
test() |