0

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 False

compiled as:

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

Any ideas?? Thanks!!

Rinks
  • 1,007
  • 2
  • 16
  • 22

4 Answers4

1

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

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • Now that you mention it, yes, although that may as well be a typo. It doesn't address the actual error message ("SyntaxError: unexpected character after line continuation character") though. –  Sep 09 '11 at 21:43
  • 2
    As an aside, I'd avoid this practice. Letting users enter arbitrary strings like this and attempting to execute them will be unreliable at best, and dangerous at worst. – g.d.d.c Sep 09 '11 at 21:44
  • I think the SyntaxError you mention is due to what g.d.d.c is saying about the space before the elif. Also I agree; be careful letting users execute arbitrary Python without limiting the builtins, etc. – xitrium Sep 09 '11 at 21:53
  • @xitrium: Then think again. That issue causes an `IndentError: Unexpected indent` or something like that. The "unexpected character after line continuation character" is caused by `\...`. –  Sep 09 '11 at 21:56
1

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
0

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?

Remi
  • 20,619
  • 8
  • 57
  • 41
0

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'

rocksportrocker
  • 7,251
  • 2
  • 31
  • 48