从代码字符串返回值 [英] Returning a value from code string

查看:71
本文介绍了从代码字符串返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含Python代码块的数据库。我已经有了一个

方式来轻松加载,编辑和保存它们。对我来说有点莫名其妙

是我如何有效地传递这些代码的一些参数,运行它,以及

以某种方式得到一个返回值。

(实际上,在撰写这篇文章的过程中,我想出了一个非常好的方法来做这件事。这是我发布的其余内容和我来的解决方案<享受我的思考过程吧!)现在我正在考虑定义一个标准函数名称,并且

使用它作为DB存储代码的入口/出口点。这个

合理吗?有更多的Pythonic方式吗?


我可能会编译代码并将字节码存储到数据库中

(除了纯文本)为了更快的执行时间。它不需要关心存储的代码是字符串还是代码对象。


如果存储的代码块不需要怎么办?什么都归还?没有标准的

功能,只需执行代码就可以更方便了。另外,将它包装在一个类中会很好:


#module test.py

class Codeobj:

def __init __(self,code = None):

如果代码:self.code = code

else:self.code =""


def __call __(self,args = None,** kwargs):

#我们可以传入名称/值字典

如果args: kwargs.update(args)

exec self.code

#如果我们没有返回,我们不需要标准功能

#anything

if locals()。has_key(''std_func_name''):

返回std_func_name(** kwargs)


if __name__ ==" __ main __":

#从DB加载代码

double =""" \

def std_func_name(n):

返回n * 2"""


addthree =""" \

def std_func_name(n):

返回n + 3"""


noreturn =" print''arg =% s''%kwargs [''arg'']"


a = Codeobj(双倍)

b = Codeobj(addthree)

c = Codeobj(noreturn)


#使用名称/值字典调用

打印a(args = {''n'':5})

#使用特定命名参数调用

print b(n = 4)

c(arg ='''foo'')

#EOF


$ python test.py

10

7

arg = foo


如果我想简化''noreturn''示例(好吧,如果有更多的

代码行,这可能会更简单),我可以定义它像

这个:


noreturn =""" \

locals()。更新(kwargs)

打印''arg =%s''%arg"""


-Kirk McDonald

Say I have a database containing chunks of Python code. I already have a
way to easily load, edit, and save them. What is slightly baffling to me
is how I can effectively pass this code some arguments, run it, and
somehow get a return value.

(Acutally, in the process of writing this post, I figured out a pretty
good way of doing it. Here''s the rest of my post and the solution I came
up with. Enjoy my thought process!)

Right now I''m thinking of just defining a standard function name, and
using that as the entry/exit point for the DB-stored code. Is this
reasonable? Is there some more Pythonic way?

I''ll probably compile the code and store the bytecode to the database
(in addition to the plain text) for faster execution time, as well. It
shouldn''t care whether the stored code is a string or a code object.

What if a stored chunk of code doesn''t need to return anything? It would
be more convenient to just execute the code without the standard
function. Also, it''d be nice to wrap this in a class:

# module test.py
class Codeobj:
def __init__(self, code=None):
if code: self.code = code
else: self.code = ""

def __call__(self, args=None, **kwargs):
# We can pass in a name/value dictionary
if args: kwargs.update(args)
exec self.code
# We don''t need a standard function if we''re not returning
# anything
if locals().has_key(''std_func_name''):
return std_func_name(**kwargs)

if __name__ == "__main__":
# Load code from the DB
double = """\
def std_func_name(n):
return n*2"""

addthree = """\
def std_func_name(n):
return n+3"""

noreturn = "print ''arg = %s'' % kwargs[''arg'']"

a = Codeobj(double)
b = Codeobj(addthree)
c = Codeobj(noreturn)

# Calling with name/value dictionary
print a(args={''n'':5})
# Calling with specific named argument
print b(n=4)
c(arg=''foo'')
# EOF

$ python test.py
10
7
arg = foo

If I wanted to simplify the ''noreturn'' example (well, if there were more
lines of code this might make it simpler), I could have defined it like
this:

noreturn = """\
locals().update(kwargs)
print ''arg = %s'' % arg"""

-Kirk McDonald

推荐答案

python test.py

10

7

arg = foo

如果我想简化''noreturn''的例子(好吧,如果有更多的

代码行,这可能会使它变得更简单),我可以将它定义为

this:


noreturn =""" \

locals()。update(kwargs)

print''arg =%s ''%arg"""


-Kirk McDonald
python test.py
10
7
arg = foo

If I wanted to simplify the ''noreturn'' example (well, if there were more
lines of code this might make it simpler), I could have defined it like
this:

noreturn = """\
locals().update(kwargs)
print ''arg = %s'' % arg"""

-Kirk McDonald


周五,2006年1月27日20:33:53 -0800,Kirk McDonald写道:
On Fri, 27 Jan 2006 20:33:53 -0800, Kirk McDonald wrote:
说我有一个包含Python代码块的数据库。我已经有了轻松加载,编辑和保存它们的方法。


为什么?


对我来说有点莫名其妙
我是如何有效地传递这些代码的一些参数,运行它,并且
以某种方式获得返回值。
Say I have a database containing chunks of Python code. I already have a
way to easily load, edit, and save them.
Why?

What is slightly baffling to me
is how I can effectively pass this code some arguments, run it, and
somehow get a return value.




你已经了解了exec。你知道eval吗?


result = eval(some_piece_of_text)


我希望数据库的内容是可信的,因为如果代码是来自不受信任的来源的
,好吧,UR pwn3d。


好​​像你正在跳过很多箍,收效甚微。

我缺少什么?

-

史蒂文。



You already know about exec. Do you know about eval?

result = eval(some_piece_of_text)

I hope the contents of the database are trusted, because if the code is
coming from an untrusted source, well, U R pwn3d.

Seems like you are jumping through a lot of hoops for very little benefit.
What am I missing?
--
Steven.


史蒂文D''Aprano写道:
Steven D''Aprano wrote:
On Fri,2006年1月27日20:33:53 -0800,Kirk McDonald写道:

On Fri, 27 Jan 2006 20:33:53 -0800, Kirk McDonald wrote:

说我有一个包含Python代码块的数据库。我已经有办法轻松加载,编辑和保存它们。
Say I have a database containing chunks of Python code. I already
have a way to easily load, edit, and save them.



为什么?


Why?




我我在Python中实现了类似Everything Engine的系统(请参阅everything2.com

和everydevel.com)。 (原文是在Perl中,并且所有

帐户都是一些非常难看的代码。)Everything成语是

引擎中的所有内容都是节点。 '节点是一个独立的单元,可以从数据库加载并保存到数据库中。可以要求节点在页面中显示

本身,它有一个所有者(用户本身就是节点),

等等。


一种节点是Superdoc,它是一个将HTML与

代码混合在一起的文档。 (我简单地将这些文件实现为mod_python PSP文档,

这些都是hunky-dory。)Superdocs基本上包含了该网站的所有重要位。另一种节点(我还在决定是否将它们称为Codenodes或Opcodes或者Pynodes)是一块可以被要求自行运行的代码。 ,并且可以在网站内的

飞行中进行编辑。因此,一个人都可以改变网站的功能,并从网站本身添加功能(只要你/ b $ b有用户权限这样做)。


-Kirk McDonald



I am implementing an Everything Engine-like system (see everything2.com
and everydevel.com) in Python. (The original is in Perl, and by all
accounts is some pretty ugly code.) The Everything idiom is that
everything in the engine is a ''node.'' A node is a discrete unit that can
be loaded from and saved to the database. A node can be asked to display
itself in the page, it has an owner (and users are themselves nodes),
and so on.

One kind of node is a Superdoc, which is a document that mixes HTML with
code. (I have simply implemented these as mod_python PSP documents,
which is all hunky-dory.) Superdocs comprise essentially all of the
important bits of the site. Another kind of node (I''m still deciding
whether to call them Codenodes or Opcodes or maybe Pynodes) is a chunk
of code that can be asked to run itself, and which can be edited, on the
fly, from within the website. Thus, one can both alter the functionality
of the site, and add functionality, from the site itself (so long as you
have the user permissions to do so).

-Kirk McDonald


这篇关于从代码字符串返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆