开发者

python compile for exec

开发者 https://www.devze.com 2023-04-03 17:25 出处:网络
I am using compile with exec to execute a python code specified by user. Below are 2 cases reprsenting the usert code that needs to be compiled. The user code is read into a string and then compiled a

I am using compile with exec to execute a python code specified by user. Below are 2 cases reprsenting the usert code that needs to be compiled. The user code is read into a string and then compiled as shown below. The compile works fine for case 1 while it throws a syntax error - "SyntaxError: unexpected character after line continuation character" for case 2

case 1 (works):

if len([1,2]) == 2:
 return True
elif len([1,2]) ==3:
 return False

case 2 (fails):

if len([1,2]) == 2:\n return True\n elif len([1,2]) ==3:\n return F开发者_开发问答alse

compiled as:

compile(userCde, '<string>','exec')

Any ideas?? Thanks!!


You have a space after the \n before the elif, causing the elif block to be indented, and therefore, a syntax error.


In case 2, there's an additional space before elif that causes this error. Also note that you can only use return inside a function, so you need a def somewhere.


Watch the spaces: I checked the following and it works:

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')

gives <code object <module> at 0280BF50, file "<string>", line 1>

edit: did you do know the eval() function?


Print your code as print repr(code), If you \n is printed as \\n instead of \n that is the source of your problem: compile interprets \n not as a end of line, but as two characters: a line continuation '\' followed by an 'n'

0

精彩评论

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