解析Python文件并评估所选函数 [英] Parse Python file and evaluate selected functions

查看:125
本文介绍了解析Python文件并评估所选函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中包含多个python函数,每个函数都有一些语句.

I have a file that contains several python functions, each with some statements.

def func1():
    codeX...
def func2():
    codeY...

codeX和codeY可以是多个语句.我希望能够解析该文件,按名称查找一个函数,然后评估该函数中的代码.

codeX and codeY can be multiple statements. I want to be able to parse the file, find a function by name, then evaluate the code in that function.

使用ast模块,我可以解析文件,找到FunctionDef对象,并获取Stmt对象的列表,但是如何将其转换为可以传递给eval的字节码?我应该使用编译模块还是解析器模块?

With the ast module, I can parse the file, find the FunctionDef objects, and get the list of Stmt objects, but how do I turn this into bytecode that I can pass to eval? Should I use the compile module, or the parser module instead?

基本上,函数defs仅用于创建单独的代码块.我希望能够获取给定名称的任何代码块,然后在eval中执行该代码(提供我自己的本地/全局范围对象).如果有比我描述的方法更好的方法,这也将有所帮助.

Basically, the function defs are just used to create separate blocks of code. I want to be able to grab any block of code given the name and then execute that code in eval (providing my own local/global scope objects). If there is a better way to do this than what I described that would be helpful too.

谢谢

推荐答案

使用Python 2.6.4:

Using Python 2.6.4:

text = """
def fun1():
    print 'fun1'

def fun2():
    print 'fun2'

"""

import ast
tree = ast.parse(text)
# tree.body[0] contains FunctionDef for fun1, tree.body[1] for fun2

wrapped = ast.Interactive(body=[a.body[1]])
code = compile(wrapped, 'yourfile', 'single')
eval(code)
fun2() # prints 'fun2'

看看ast doc中的语法: http://docs.python .org/library/ast.html#abstract-grammar .顶层语句必须是Module,Interactive或Expression,因此您需要在其中之一中包装def.

Take a look at grammar in ast doc: http://docs.python.org/library/ast.html#abstract-grammar. Top-level statement must be either Module, Interactive or Expression, so you need to wrap function def in one of those.

这篇关于解析Python文件并评估所选函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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