Use newlines \n with the command python -c

How i can execute a piece of code with newlines with the -c option of the python command:

# This don't work !
python -c "print('first line') \n print('second line')"

I try too with reading from py file :

# test.py
print("first line")
print("second line")

with next shell

code==$(cat test.py)
python -c $code

But I have a beautiful error too

Here the sequence \n inserts the literal characters \ and n so the Python interpreter does not get a newline.

However if your shell is capable of inserting control characters you can insert a newline. For example in bash:

$ python3 -c $'print(1)\nprint(2)'
1
2

Note that to give an actual backslash to Python you have to double it inside $'...':

$ python3 -c $'print(r"a\\b")'
a\b

I have no idea what is “next shell” but in bash and probably any POSIX-compliant shell you just need to use double quotes to keep the whitespace characters:

$ code=$(cat test1.py)   # Assignment is an exception. Here double quotes are not necessary.
$ python3 -c "$code"
first line
second line
1 Like

Try replacing the \n with ;

python -c "print('first line') ; print('second line')"
``'
This ends a command and starts a new one, tested on windows 10

With zsh and bash this works:

$ python3 -c "import sys
print(sys.path)
"
['', '/usr/lib64/python310.zip', '/usr/lib64/python3.10', '/usr/lib64/python3.10/lib-dynload', '/home/barry/.local/lib/python3.10/site-packages', '/usr/lib64/python3.10/site-packages', '/usr/lib/python3.10/site-packages']