0

If I do:

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

python -c 'print("Hello")'

It works as expected. However,

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

Fails.

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

How to handle multi-line (and indented) python code using the -c option?

00__00__00
  • 4,834
  • 9
  • 41
  • 89

1 Answers1

3

The \n is treated as two characters (backslash, the character n) by the shell, and that's invalid syntax in Python, so you get the error.

To fix this in Bash, use $'string':

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

Note that the space after the newline (\n print) will count as invalid indentation (now by Python, not the shell), so I removed it.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • How can I apply this with subprocess.check_output() ? – 00__00__00 Mar 18 '20 at 19:10
  • 1
    How exactly are you planning to use this with `subprocess`? And also why? You can execute Python code right from within Python, no need for external programs. See `exec`, for example. But be careful! `exec` will execute any Python code, so don't use it to run code provided by the user, although there are ways to sanitize the input and the runtime environment. – ForceBru Mar 18 '20 at 19:23
  • unfortunately I need subprocess as the execution must start from a remote interpreter....I will accept your answer anyway – 00__00__00 Mar 18 '20 at 19:33