Python Forum

Full Version: command line: python -c 'code here'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
when tying to execute multi line code through the -c option of the python interpreter itself, i have not gotten anything to work. is this suppose to even be able to work? i have gotten it to work using the exec() function by giving it a multi line string so my code, at first, looks like one statement. is there a better way?
This seems to be a working example:
I tried it in 3.6 doesn't appear to work
It works for me
λ python3 -c $'print("foo")\nprint("bar")' foo bar
$ python3 -c 'print("foo"); print("bar")'
Works here too. Python 3.6
The challenge was to execute multi line code.
It's not a challenge.

Just like echo command if you don't close the quotes you can write as many lines as you want:

$ python3 -c "import requests
from bs4 import BeautifulSoup
html = requests.get('').content
soup = BeautifulSoup(html, 'lxml')
print('\n', soup.title.text, '\n')"

 Python Forum 
playing around with this some more i find the ; is not acting like a newline because it does not handle indentation normally and it cannot handle 2 or more in a row.

it come down to what is being given to python by the shell. it needs to get the newline as one byte with the newline code, not two bytes with \ and n which is what you often get when you type \ and n (there are a couple exceptions).
You can use a shell variable with a here document

read -r -d '' variable <<'EOF'
import sys
def hi():
    print('hello world')

python3 -c "$variable"
The advantage of here documents is that you don't have to worry about quotes and double quotes.