How to execute Python inline from a bash shell

65,086

Solution 1

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

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

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

Another way is to use the e module

eg.

$ python -me 1 + 1
2
Share:
65,086
Sean
Author by

Sean

Fun loving computer science major

Updated on November 19, 2020

Comments

  • Sean
    Sean over 3 years

    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"'
    
  • Mike Müller
    Mike Müller about 11 years
    Interesting. But you need to have an extra install.
  • beldaz
    beldaz over 6 years
    Also useful to remember that you can use ; to separate statements, e.g., python -c 'import foo; foo.bar()'
  • Jay Taylor
    Jay Taylor almost 6 years
    Useless unless you've already run pip install e. For a standard python install, this produces the error: No module named e.
  • do-me
    do-me over 3 years
    Doesn't work for me on python 3.8.Traceback (most recent call last): File "<string>", line 1, in <module> NameError: name 'Hi' is not defined
  • Mike Müller
    Mike Müller over 3 years
    Make sure "Hi" is in quotes.