簡體   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