我正在使用exec和exec来执行用户指定的python代码。下面是2个需要编译的用于代码的usert代码。用户代码读入字符串,然后编译如下所示。对于案例1,编译工作正常,但它会引发语法错误 - 案例2中的“SyntaxError:行后续字符后的意外字符”
案例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')
任何想法? 谢谢!
答案 0 :(得分:1)
在elif之前的\n
之后有一个空格,导致elif块缩进,因此出现语法错误。
答案 1 :(得分:1)
在案例2中,elif
之前还有一个空格导致此错误。另请注意,您只能在函数内部使用return,因此在某处需要def
。
答案 2 :(得分: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()
功能吗?
答案 3 :(得分:0)
将代码打印为print repr(code)
,如果\n
打印为\\n
而不是问题来源\n
:编译解释\n
不作为行尾,而是作为两个字符:行继续'\'
后跟'n'