简体   繁体   English

用于脚本转换的Python即时功能

[英]Python on-the-fly function to script conversion

Is there a reasonably natural way of converting python function to standalone scripts? 是否有一种将python函数转换为独立脚本的合理自然方式? Something like: 就像是:

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

and NOT like: 而不喜欢:

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

You can turn any "object" into a function by defining the __call__ method on it (see here .) Hence, if you want to compartmentalize some state with the computations, as long as what you've provided from the very top to the bottom of a class can be pickled, then that object can be pickled. 您可以通过在其上定义__call__方法将任何“对象”转换为函数(请参阅此处 。)因此,如果您想将某些状态与计算区分开来,只要您从顶部到底部提供的内容一个类可以被腌制,然后该对象可以被腌制。

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

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

That's the easy cheater way. 这是简单的骗子方式。 Why pickling? 为什么要酸洗? Anything that can be pickled can be sent to another process without fear. 任何可以腌制的东西都可以毫无畏惧地发送到另一个过程。 You're forming a "poor man's closure" by using an object like this. 通过使用这样的对象,你正在形成一个“穷人的封闭”。

(There's a nice post about the "marshal" library here on SO if you want to truly pickle a function.) (如果你想真正挑选一个功能,那么这里有关于 “元帅”库的好帖子。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM