【问题标题】:We need to pickle any sort of callable我们需要腌制任何类型的可调用对象
【发布时间】:2011-09-08 05:46:36
【问题描述】:

最近有人提出了一个问题,即一些 Python 代码试图通过使用腌制进程来促进分布式计算。显然,该功能在历史上是可能的,但出于安全原因,相同的功能被禁用。在第二次尝试通过套接字传输函数对象时,只传输了引用。如果我错了,请纠正我,但我不认为这个问题与 Python 的后期绑定有关。假设进程和线程对象不能被腌制,有没有办法传输可调用对象?我们希望避免为每个作业传输压缩的源代码,因为这可能会使整个尝试变得毫无意义。出于可移植性的原因,只能使用 Python 核心库。

【问题讨论】:

  • 每当您发现自己在问“X 不允许出于安全原因;我该如何解决这个问题?”时,您应该准备好一个 详细说明您需要解决它的原因。安全是一件严肃的事情。
  • @Karl,这是一个很好的观点。说需要一种解决方法是夸大其词。我犯了一个错误,甚至建议了简单的出路。我会坚持下去,从 Artur 的建议开始。
  • 如果代码是纯python,那么它与python核心库一样可移植。我有一个纯 Python 序列化程序,它可以腌制任何可调用的……它被用作纯 Python 并行和分布式计算库的主干。它是可移植的……并且可以构建分层并行和分布式并行映射和管道的网络。我的观点是,如果一个包是纯 python,你不应该排除它——如果它还没有安装,你只需将它安装到分布式集群上的用户区域。查看dill 包,它基本上是pickle copy_reg 调用的集合。

标签: python distributed-computing


【解决方案1】:

您可以编组字节码并腌制其他功能:

import marshal
import pickle

marshaled_bytecode = marshal.dumps(your_function.func_code)
# In this process, other function things are lost, so they have to be sent separated.
pickled_name = pickle.dumps(your_function.func_name)
pickled_arguments = pickle.dumps(your_function.func_defaults)
pickled_closure = pickle.dumps(your_function.func_closure)
# Send the marshaled bytecode and the other function things through a socket (they are byte strings).
send_through_a_socket((marshaled_bytecode, pickled_name, pickled_arguments, pickled_closure))

在另一个python程序中:

import marshal
import pickle
import types

# Receive the marshaled bytecode and the other function things.
marshaled_bytecode, pickled_name, pickled_arguments, pickled_closure = receive_from_a_socket()
your_function = types.FunctionType(marshal.loads(marshaled_bytecode), globals(), pickle.loads(pickled_name), pickle.loads(pickled_arguments), pickle.loads(pickled_closure))

并且函数内部对全局变量的任何引用都必须在接收函数的脚本中重新创建。

在 Python 3 中,使用的函数属性为 __code____name____defaults____closure__

请注意send_through_a_socketreceive_from_a_socket 实际上并不存在,您应该将它们替换为通过套接字传输数据的实际代码。

【讨论】:

  • That 似乎部分功能正常。
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
相关资源
最近更新 更多