如果您使用dill,它可以让您将__main__ 视为一个python 模块(大部分情况下)。因此,您可以序列化交互式定义的类等。 dill 也(默认情况下)可以将类定义作为泡菜的一部分传输。
>>> class MyTest(object):
... def foo(self, x):
... return self.x * x
... x = 4
...
>>> f = MyTest()
>>> import dill
>>>
>>> with open('test.pkl', 'wb') as s:
... dill.dump(f, s)
...
>>>
然后关闭解释器,并通过 TCP 发送文件test.pkl。在您的远程机器上,现在您可以获取类实例了。
Python 2.7.9 (default, Dec 11 2014, 01:21:43)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('test.pkl', 'rb') as s:
... f = dill.load(s)
...
>>> f
<__main__.MyTest object at 0x1069348d0>
>>> f.x
4
>>> f.foo(2)
8
>>>
但是如何获取类定义呢?所以这不是你想要的。然而,以下是。
>>> class MyTest2(object):
... def bar(self, x):
... return x*x + self.x
... x = 1
...
>>> import dill
>>> with open('test2.pkl', 'wb') as s:
... dill.dump(MyTest2, s)
...
>>>
那么发送文件后……就可以得到类定义了。
Python 2.7.9 (default, Dec 11 2014, 01:21:43)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('test2.pkl', 'rb') as s:
... MyTest2 = dill.load(s)
...
>>> print dill.source.getsource(MyTest2)
class MyTest2(object):
def bar(self, x):
return x*x + self.x
x = 1
>>> f = MyTest2()
>>> f.x
1
>>> f.bar(4)
17
所以,在dill 中,有dill.source,它具有可以检测函数和类的依赖关系的方法,并将它们与泡菜一起使用(大部分情况下)。
>>> def foo(x):
... return x*x
...
>>> class Bar(object):
... def zap(self, x):
... return foo(x) * self.x
... x = 3
...
>>> print dill.source.importable(Bar.zap, source=True)
def foo(x):
return x*x
def zap(self, x):
return foo(x) * self.x
所以这不是“完美的”(或者可能不是预期的)......但它确实序列化了动态构建方法的代码及其依赖项。您只是没有获得课程的其余部分 - 但在这种情况下不需要课程的其余部分。
如果你想得到所有东西,你可以腌制整个会话。
>>> import dill
>>> def foo(x):
... return x*x
...
>>> class Blah(object):
... def bar(self, x):
... self.x = (lambda x:foo(x)+self.x)(x)
... x = 2
...
>>> b = Blah()
>>> b.x
2
>>> b.bar(3)
>>> b.x
11
>>> dill.dump_session('foo.pkl')
>>>
然后在远程机器上...
Python 2.7.9 (default, Dec 11 2014, 01:21:43)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('foo.pkl')
>>> b.x
11
>>> b.bar(2)
>>> b.x
15
>>> foo(3)
9
最后,如果您希望透明地为您“完成”传输,您可以使用pathos.pp 或ppft,它们提供将对象发送到第二个python 服务器(在远程机器上)或python 的能力过程。他们在后台使用dill,然后通过网络传递代码。
>>> class More(object):
... def squared(self, x):
... return x*x
...
>>> import pathos
>>>
>>> p = pathos.pp.ParallelPythonPool(servers=('localhost,1234',))
>>>
>>> m = More()
>>> p.map(m.squared, range(5))
[0, 1, 4, 9, 16]
servers 参数是可选的,这里只是连接到端口 1234 上的本地机器……但如果您使用远程机器名称和端口代替(或同时使用),您将启动远程机器——“毫不费力”。
在此处获取dill、pathos 和ppft:https://github.com/uqfoundation