How to execute Python inline from a bash shell
Asked Answered
J

4

127

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"'
Jello answered 4/6, 2013 at 1:3 Comment(1)
-c is the second option described in the man page.Kyanize
T
212

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).
Tayyebeb answered 4/6, 2013 at 1:7 Comment(5)
Also useful to remember that you can use ; to separate statements, e.g., python -c 'import foo; foo.bar()'Damali
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 definedSuperior
Make sure "Hi" is in quotes.Acidulent
Also how do I access a variable in the commandFoxhound
You can turn on interactive mode with -i: python -i -c 'a = 5' >>> a 5Acidulent
P
39

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"
Puerilism answered 5/6, 2013 at 10:53 Comment(0)
S
38

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
Surfbird answered 13/11, 2019 at 9:12 Comment(2)
How can redirect the output into a text file (under bash)? I am trying to add "> temp.txt" after the command and also to use a pipe and other ideas, but the file is zero length.Acaudal
OK, figured that out. You need to add the "> temp.txt" after the first HEREDOC on the first line in your example., i.e., do: "$ python <<HEREDOC > temp.txt"Acaudal
T
1

Another way is to use the e module

eg.

$ python -me 1 + 1
2
Tidings answered 4/6, 2013 at 1:24 Comment(2)
Interesting. But you need to have an extra install.Acidulent
Useless unless you've already run pip install e. For a standard python install, this produces the error: No module named e.Wonted

© 2022 - 2024 — McMap. All rights reserved.