繁体   English   中英

如何从bash脚本执行多行python代码?

[英]How to execute multiline python code from a bash script?

我需要扩展一个shell脚本(bash)。 由于我对python更熟悉,我想通过编写一些python代码来实现这一点,这些代码依赖于shell脚本中的变量。 添加额外的python文件不是一种选择。

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

不太可读。

我更喜欢将我的python代码指定为多行字符串,然后执行它。

使用here-doc:

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

这个SO答案的坦克我自己找到了答案:

#!/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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM