How to execute multiline python code with bash script?

I need to expand the shell script (bash). Since I am much more familiar with python, I want to do this by writing a few lines of python code, which depends on the variables from the shell script. Adding an additional python file is not an option.

result=`python -c "import stuff; print('all $code in one very long line')"` 

not readable.

I would prefer to specify my python code as a multi-line string and then execute it.

+4
source share
2 answers

Use here-doc:

result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
+5
source

Tanks this answer SO> I myself found the answer:

#!/bin/bash

# some bash code
END_VALUE=10

PYTHON_CODE=$(cat <<END
# python code starts here
import math

for i in range($END_VALUE):
    print(i, math.sqrt(i))

# python code ends here
END
)

# use the 
res="$(python3 -c "$PYTHON_CODE")"

# continue with bash code
echo "$res"
+1
source

Source: https://habr.com/ru/post/1658272/


All Articles