如何从 bash 脚本执行多行 python 代码?
How to execute multiline python code from a bash script?
我需要扩展 shell 脚本 (bash)。由于我对 python 更加熟悉,因此我想通过编写一些依赖于 shell 脚本变量的 python 代码行来做到这一点。添加额外的 python 文件不是一个选项。
result=`python -c "import stuff; print('all $code in one very long line')"`
可读性不是很好。
我更愿意将我的 python 代码指定为多行字符串,然后执行它。
使用此处文档:
result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
感谢 this SO 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"
我需要扩展 shell 脚本 (bash)。由于我对 python 更加熟悉,因此我想通过编写一些依赖于 shell 脚本变量的 python 代码行来做到这一点。添加额外的 python 文件不是一个选项。
result=`python -c "import stuff; print('all $code in one very long line')"`
可读性不是很好。
我更愿意将我的 python 代码指定为多行字符串,然后执行它。
使用此处文档:
result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
感谢 this SO 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"