0

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

3 Answers 3

2

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'))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.