如何将多行缩进脚本作为字符串传递给 python 解释器 (-c)

how to pass a multi-line indented script as a string to python interpreter (-c)

如果我这样做:

python -c 'print("Hello");print("Hello") '

python -c 'print("Hello")'

它按预期工作。然而,

python -c 'print("Hello") \n print("Hello") '

失败。

File "<string>", line 1
    print("Hello") \n print("Hello") 
                                    ^
SyntaxError: unexpected character after line continuation character

如何使用 -c 选项处理多行(和缩进)python 代码?

\n 被 shell 视为 两个 字符(反斜杠,字符 n),这是无效语法Python,所以你得到错误。

要在 Bash 中解决此问题,请使用 $'string':

forcebru$ python -c $'print("Hello") \nprint("Hello") '
Hello
Hello
forcebru$ 

请注意,换行符 (\n print) 之后的 space 将被视为无效缩进(现在是 Python,而不是 shell),所以我将其删除.