Python Forum
command line: python -c 'code here'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
command line: python -c 'code here'
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
This seems to be a working example: https://stackoverflow.com/questions/2715...-in-python
I tried it in 3.6 doesn't appear to work
Reply
#3
It works for me
Output:
λ python3 -c $'print("foo")\nprint("bar")' foo bar
Reply
#4
$ python3 -c 'print("foo"); print("bar")'
foo
bar
Works here too. Python 3.6
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
The challenge was to execute multi line code.
Reply
#6
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('http://python-forum.io').content
soup = BeautifulSoup(html, 'lxml')
print('\n', soup.title.text, '\n')"

 Python Forum 
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
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).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#8
You can use a shell variable with a here document
#!/bin/bash

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

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Monitor specific line of code and get alert Olimpiarob 0 1,515 Jul-08-2020, 10:06 AM
Last Post: Olimpiarob
  Python to interact with the Linux Command Line - Centos/RHEL redhat_boy 2 2,196 May-10-2020, 08:33 AM
Last Post: redhat_boy
  Beautiful soup opens python command line and nothing happens Prince_Bhatia 4 4,492 Aug-01-2017, 11:50 AM
Last Post: Prince_Bhatia

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020