开发者

Simultaneous eval and exec

Is there a way to get python to do an evaluation and execution on a string? I have a file which contains a bunch of expressions that need to be calculated, maybe something like this.

f1(ifilter(myfilter,x))
f2(x)*f3(f4(x)+f5(x))

I run through the file and eval the expressions.

Some of the expressions may want to save their work after doing an expensive operation

y = g(x); h(y)+j(y)

Unfortunately, y=g(x) requires an exec, but getting the val开发者_运维百科ue of h+j is an eval. How does this work?


Try using the builtin compile(). When you use it in single mode it handles both of the cases that you want. For example:

compile('3+4','<dummy>','single')

will return a compiled code object. You can execute it with exec() or eval() :

>>> exec(compile('3+4','<dummy>','single'))
7
>>> exec(compile('x=3+4','<dummy>','single'))
>>> print x
7
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜