【问题标题】:How to execute multiline python code from a bash script?如何从 bash 脚本执行多行 python 代码?
【发布时间】:2017-03-01 18:57:57
【问题描述】:

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

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

可读性不强。

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

【问题讨论】:

    标签: python bash multiline


    【解决方案1】:

    使用此处的文档:

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

    【讨论】:

      【解决方案2】:

      坦克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"
      

      【讨论】:

      • 如何将两个变量返回到“res”?谢谢。
      • res 包含一个带有输出的字符串。所以你必须解析字符串。 a, b = "foo", "bar" 之类的构造在 bash 中是不可能的。
      • 这很棒,因为它不会占用stdin
      猜你喜欢
      • 2020-08-18
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2023-03-20
      • 1970-01-01
      • 2015-05-09
      • 2018-07-02
      相关资源
      最近更新 更多