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!!

4
  • 3
    What are you asking? The second string simply isn't valid Python code. Commented Sep 9, 2011 at 21:41
  • use triple quoted strings with code 1 Commented Sep 9, 2011 at 21:51
  • If I remove the blank before "elif" I get a "return outside function" Commented Sep 9, 2011 at 21:51
  • What are you really trying to do? Why can't the user just, you know, call up a Python prompt and use it? Commented Sep 9, 2011 at 21:58

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
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: Then think again. That issue causes an IndentError: Unexpected indent or something like that. The "unexpected character after line continuation character" is caused by \....
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.

Comments

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?

Comments

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.