python 编译用于 exec
我正在使用编译和执行的方法来运行用户指定的Python代码。下面有两个例子,代表需要编译的用户代码。用户的代码被读取为一个字符串,然后像下面这样进行编译。对于案例1,编译正常,但对于案例2,它却抛出了一个语法错误——“SyntaxError: unexpected character after line continuation character”。
案例1(正常运行):
if len([1,2]) == 2:
return True
elif len([1,2]) ==3:
return False
案例2(失败):
if len([1,2]) == 2:\n return True\n elif len([1,2]) ==3:\n return False
编译如下:
compile(userCde, '<string>','exec')
有什么想法吗?谢谢!!
4 个回答
0
注意空格的问题:我检查了以下内容,它是可以工作的:
template = "def myfunc(a):\n{0}\nmyfunc([1,2])"
code = " if len(a) == 2:\n return True\n elif len(a) ==3:\n return False"
compile(template.format(code), '<string>','exec')
结果是 <code object <module> at 0280BF50, file "<string>", line 1>
补充说明:你知道 eval()
这个函数吗?
1
在\n
之后的elif前面有一个空格,这导致elif的代码块缩进了,所以出现了语法错误。
1
在第二种情况下,elif
前面多了一个空格,这就导致了错误。另外要注意,return
只能在函数里面使用,所以你需要在某个地方定义一个 def
。