Python has an option that allows us to pass python statements as an argument to the program.

An example usage is

$ python -c "print(\"I'm running Python.\")"
I'm running Python.

In Python's man page we read

when called with -c command, it executes the
       Python statement(s) given as command.  Here command may contain  multi‐
       ple  statements  separated by newlines.

I'm trying to pass in multiple lines, but can't:

$ python -c "print(0)\nprint(1)"
  File "<string>", line 1
SyntaxError: unexpected character after line continuation character

I also tried Here-documents without success. How do I make this work?


Use here-doc's supported by your shell, instead of relying on the own options from python. This way you need to do a multi-level nesting of your quotes and type your code free-form as you can do on a script.

The - after the python executable means that the commands to run are coming from the standard input which you are feeding from the here-doc. Most utilities implement this, i.e. a - after a command means that an input is coming over from standard input which needs to be parsed.

python - <<'EOF'
print("I'm running Python.")
print("Are you now?")

Also literal escaped \n are not recognized by the shell without commands that make use of them like printf or echo -e. The string within ".." is processed by the underlying shell before passing it over to the executable. Since there is no special processing available for the literal \n, the shell does not expand it over to multiple lines.

You should still generate the line break implicitly while using -c by pressing the Enter key on the terminal and continue typing the next set of commands

python -c "print(0)
> print(1)"

One other way to still use python -c and do this would be to defined the string in such a way that the embedded newlines are parsed within "..". One way to do in bash/zsh would be to use ANSI-C Quoting and do

python -c $'print(0)\nprint(1)'

i.e. within the $'..' the \n and few other escape sequences are expanded by the shell before passing it over the executable. Now your python interpreter sees two separate lines passed to it.

Also there is very well written cross-site dupe on StackOverflow - Executing multi-line statements in the one-line command-line? explaining this.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.