有没有简单的方法来腌制python函数(或以其他方式序列化其代码)? [英] Is there an easy way to pickle a python function (or otherwise serialize its code)?

查看:101
本文介绍了有没有简单的方法来腌制python函数(或以其他方式序列化其代码)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过网络连接传输一个函数(使用asyncore)。有没有简单的方法来序列化一个Python函数(至少在这种情况下,将没有副作用)像这样的传输?



我会喜欢有一对类似于这些功能:

  def transmit(func):
obj = pickle.dumps( func)
[通过网络发送obj]

def receive():
[从网络接收obj]
func = pickle.loads(s)
func()


解决方案

字节码,然后在呼叫者身上重建它。可以使用元帅模块对代码对象进行序列化,然后将其重新组合成一个函数。即:
$ b $ pre $ code $ import
def foo(x):return x * x
code_string = marshal。转储(foo.func_code)

然后在远程进程中(传输code_string之后):



pre $ 导入编组,类型

code = marshal.loads(code_string)
func = types.FunctionType代码,globals(),some_func_name)

func(10)#给出100

一些注意事项:


  • marshal的格式(任何python字节码)可能不兼容主python版本。


  • 如果函数引用了全局变量(包括导入的模块,其他功能等),您需要将它们串行化,或者在远程端重新创建它们。我的例子只是给它提供了远程进程的全局名称空间。

  • 你可能需要做更多的工作来支持更复杂的情况,比如闭包或者生成器函数。

I'm trying to transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?

I would ideally like to have a pair of functions similar to these:

def transmit(func):
    obj = pickle.dumps(func)
    [send obj across the network]

def receive():
    [receive obj from the network]
    func = pickle.loads(s)
    func()

解决方案

You could serialise the function bytecode and then reconstruct it on the caller. The marshal module can be used to serialise code objects, which can then be reassembled into a function. ie:

import marshal
def foo(x): return x*x
code_string = marshal.dumps(foo.func_code)

Then in the remote process (after transferring code_string):

import marshal, types

code = marshal.loads(code_string)
func = types.FunctionType(code, globals(), "some_func_name")

func(10)  # gives 100

A few caveats:

  • marshal's format (any python bytecode for that matter) may not be compatable between major python versions.

  • Will only work for cpython implementation.

  • If the function references globals (including imported modules, other functions etc) that you need to pick up, you'll need to serialise these too, or recreate them on the remote side. My example just gives it the remote process's global namespace.

  • You'll probably need to do a bit more to support more complex cases, like closures or generator functions.

这篇关于有没有简单的方法来腌制python函数(或以其他方式序列化其代码)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆