在 Python 中解析和评估任意源代码

rad*_*rad -1 python

我有一个这样的文件:

a = 1
some rubbish
b = 2
some other rubbish
c = a + b
Run Code Online (Sandbox Code Playgroud)

我想知道 的价值c

我的想法是逐行评估文件,因为语法仅包含简单的算术运算。然而,问题是该文件还包含不是有效 python 表达式的行,我想简单地跳过这些行。

我并不担心该文件包含任何恶意代码,但我希望评估发生在某种“安全环境”(不同的命名空间?)中,以免干扰其余(主)代码。

moz*_*way 6

如果您想检查每一行并删除所有无效的 python 行,您可以使用ast.parse. 删除触发 a 的行SyntaxError

text = '''a = 1
some rubbish
b = 2
some other rubbish
c = a + b
'''

from ast import parse

for line in text.splitlines():
    try:
        parse(line)
        print(line)
    except SyntaxError:
        pass
Run Code Online (Sandbox Code Playgroud)

输出:

a = 1
b = 2
c = a + b
Run Code Online (Sandbox Code Playgroud)

注意。使用简单的print演示,但您可以将这些行写入文件中:

from ast import parse

with open('test.py') as f, open('out.py', 'w') as f_out:
    for line in f:
        try:
            parse(line)
            f_out.write(line)
        except SyntaxError:
            pass
Run Code Online (Sandbox Code Playgroud)