Home > Blockchain >  Why does exec raise a syntax error when given python string?
Why does exec raise a syntax error when given python string?

Time:08-22

I have this python code

while 1:
    exec(input())

when I enter import os \nos.system("echo 1") I get this error

  File "<string>", line 1
    import os \nos.system("echo 1")
                                  ^
SyntaxError: unexpected character after line continuation character

CodePudding user response:

The problem is that you're using \n within the exec, which as @The Thonnu mentioned causes problems when parsing.

Try entering import os; os.system("echo 1") instead.

Semicolons can be used in Python to separate different lines as an alternative to semicolons.

If you must use \n in your input, you can also use:

while 1:
    exec(input().replace('\\n', '\n'))

CodePudding user response:

When you enter the line:

import os \nos.system("echo 1")

In Python, this string actually looks like this:

import os \\nos.system("echo 1")

Because it's trying to treat your input as literally having a \, which requires a \\. It doesn't treat your \n as a newline.

You could remove the escape yourself:

cmd = input()
exec(cmd.replace("\\n", "\n"))

CodePudding user response:

exec reads the \n as a backslash and then n ('\\n') not '\n'.

A backslash is a line continuation character which is used at the end of a line, e.g.:

message = "This is really a long sentence " \
          "and it needs to be split across mutliple " \
          "lines to enhance readibility of the code"

If it recieves a character after a backslash, it raises an error.

You can use a semicolon to indicate a new expression:

import os; os.system("echo 1")

Or, replace the '\n's in your code:

exec(input().replace('\\n', '\n'))
  • Related