我们需要腌任何可腌的

发布于 2021-01-29 18:23:38

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

关注者
0
被浏览
44
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以编组字节码并腌制其他函数:

    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实际上不存在的,你应该通过实际的代码通过插座替换它们传送数据。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看