0

是否有一种合理自然的方式将 python 函数转换为独立脚本?就像是:

def f(): 
    # some long and involved computation

script = function_to_script(f) # now script is some sort of closure, 
                               # which can be run in a separate process
                               # or even shipped over the network to a 
                               # different host

不喜欢:

script = open("script.py", "wt")
script.write("#!/usr/bin/env python")
...
4

1 回答 1

2

您可以通过在其上定义方法将任何“对象”转换为函数__call__(请参见此处。)因此,如果您想通过计算划分某些状态,只要您从顶部到底部提供的内容可以腌制一个类,然后可以腌制该对象。

class MyPickledFunction(object):
    def __init__(self, *state):
        self.__state = state

    def __call__(self, *args, **kwargs):
        #stuff in here

这是最容易的骗子方法。为什么要腌制?任何可以腌制的东西都可以毫无顾忌地发送到另一个进程。通过使用这样的对象,您正在形成一个“穷人的封闭”。

(如果你想真正腌制一个函数,那么这里有一篇关于“元帅”库的好帖子。)

于 2013-03-28T03:48:48.387 回答