简体   繁体   中英

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

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

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

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, eg:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM