23

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

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

is not very readable.

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

2 Answers 2

26

Use a here-doc:

result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
2
  • If one does not need the return value, is it then possible to ommit the "$("?
    – Siete
    Jan 5 at 9:55
  • 1
    Yes. That's just the normal use of a here-document.
    – Barmar
    Jan 5 at 16:37
7

Tanks to this SO answer I found the answer myself:

#!/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"
3
  • How to return two variables to "res"? Thanks.
    – Lion Lai
    Apr 8, 2020 at 8:48
  • 1
    res contains a string with the output. So you have to parse the string. Constructs like a, b = "foo", "bar" are imho not possible in bash.
    – cknoll
    Apr 10, 2020 at 8:36
  • This is great because it doesn't tie up stdin
    – jez
    Aug 1, 2020 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.