Dark Launch

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:

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

Using cat:

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

Pass bash variable to python script through stdin:

Bash
some_bash_var="world"
 
script="
import sys
name = sys.stdin.read().rstrip()
print('hello ' + name)
"
echo "${some_bash_var}" | python -c "${script}"

Output:

Bash
$ some_bash_var="world"
$ script="
→ import sys
→ name = sys.stdin.read().rstrip()
→ print('hello ' + name)
→ "
$ echo "${some_bash_var}" | python -c "${script}"
hello world

Comments


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