我有这个python代码
while 1:
exec(input())
当我输入import os \nos.system("echo 1")
时,我会得到这个错误
File "<string>", line 1
import os \nos.system("echo 1")
^
SyntaxError: unexpected character after line continuation character
发布于 2022-08-21 15:51:02
问题在于您在\n
中使用exec
,正如@ Thonnu所提到的那样,这会导致解析时出现问题。
尝试输入import os; os.system("echo 1")
。
在Python中,分号可以用来分隔不同的行,作为分号的替代。
如果必须在输入中使用\n
,也可以使用:
while 1:
exec(input().replace('\\n', '\n'))
发布于 2022-08-21 15:50:10
exec
将\n
读入反斜杠,然后n ('\\n'
)而不是'\n'
。
反斜杠是行连续字符,用于行尾,例如:
message = "This is really a long sentence " \
"and it needs to be split across mutliple " \
"lines to enhance readibility of the code"
如果在反斜杠后接收字符,则会引发错误。
您可以使用分号来表示一个新表达式:
import os; os.system("echo 1")
或者,替换代码中的'\n'
:
exec(input().replace('\\n', '\n'))
发布于 2022-08-21 15:52:16
当您进入该行时:
import os \nos.system("echo 1")
在Python中,这个字符串实际上如下所示:
import os \\nos.system("echo 1")
因为它试图将您的输入看作是有一个\
,这需要一个\\
。它不把您的\n
当作换行符。
你可以自己移除逃逸:
cmd = input()
exec(cmd.replace("\\n", "\n"))
https://stackoverflow.com/questions/73435923
复制相似问题