How to execute Python inline from a bash shell

PythonShellInlineExecution

Python Problem Overview


Is there a Python argument to execute code from the shell without starting up an interactive interpreter or reading from a file? Something similar to:

perl -e 'print "Hi"'

Python Solutions


Solution 1 - Python

This works:

python -c 'print("Hi")'
Hi

From the manual, man python:

> -c command > Specify the command to execute (see next section). This termi- > nates the option list (following options are passed as arguments > to the command).

Solution 2 - Python

Another way is to you use bash redirection:

python <<< 'print "Hi"'

And this works also with perl, ruby, and what not.

p.s.

To save quote ' and " for python code, we can build the block with EOF

c=`cat <<EOF
print(122)
EOF`
python -c "$c"

Solution 3 - Python

A 'heredoc' can be used to directly feed a script into the python interpreter:

python <<HEREDOC
import sys
for p in sys.path:
  print(p)
HEREDOC


/usr/lib64/python36.zip
/usr/lib64/python3.6
/usr/lib64/python3.6/lib-dynload
/home/username/.local/lib/python3.6/site-packages
/usr/local/lib/python3.6/site-packages
/usr/lib64/python3.6/site-packages
/usr/lib/python3.6/site-packages

Solution 4 - Python

Another way is to use the e module

eg.

$ python -me 1 + 1
2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeanView Question on Stackoverflow
Solution 1 - PythonMike MüllerView Answer on Stackoverflow
Solution 2 - PythonmichaelmeyerView Answer on Stackoverflow
Solution 3 - PythonawltuxView Answer on Stackoverflow
Solution 4 - PythonJohn La RooyView Answer on Stackoverflow