How to Include Python Script in Bash Script

To run a multiline python script in a bash shell script from the command line, do the following:

python - <<EOF
import random
print(random.random())
EOF

Using cat:

cat <<EOF | python -
import random
print(random.random())
EOF

Pass bash variable to python script through stdin:

some_bash_var="world"

script="
import sys
name = sys.stdin.read().rstrip()
print('hello ' + name)
"

echo "${some_bash_var}" | python -c "${script}"

Output:

$ some_bash_var="world"
$ script="
→ import sys
→ name = sys.stdin.read().rstrip()
→ print('hello ' + name)
→ "

$ echo "${some_bash_var}" | python -c "${script}"
hello world
View this page on GitHub.
Posted .

1 comment

  1. anonymous
    Alternatively, something like this works as well: eval python - < EOF import sys from pprint import pprint pprint(sys.path) EOF

Leave a Reply