您可以编组字节码并腌制其他函数:
import marshalimport picklemarshaled_bytepre = marshal.dumps(your_function.func_pre)# 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 bytepre and the other function things through a socket (they are byte strings).send_through_a_socket((marshaled_bytepre, pickled_name, pickled_arguments, pickled_closure))
在另一个python程序中:
import marshalimport pickleimport types# Receive the marshaled bytepre and the other function things.marshaled_bytepre, pickled_name, pickled_arguments, pickled_closure = receive_from_a_socket()your_function = types.FunctionType(marshal.loads(marshaled_bytepre), globals(), pickle.loads(pickled_name), pickle.loads(pickled_arguments), pickle.loads(pickled_closure))
并且必须在接收该函数的脚本中重新创建该函数内部对全局变量的任何引用。
在Python 3,功能属性使用的是
__pre__,
__name__,
__defaults__和
__closure__。
请大家注意,
send_through_a_socket而
receive_from_a_socket实际上不存在的,你应该通过实际的代码通过插座替换它们传送数据。



