gpt4 book ai didi

python - 如何将python变量传递给azure databricks笔记本中的shell脚本?

转载 作者:行者123 更新时间:2023-12-02 01:41:00 25 4
gpt4 key购买 nike

如何将 python 变量从 %python cmd 传递到 shell 脚本 %sh,在 azure databricks 笔记本中..?

notebook example

最佳答案

根据我的经验,对于当前场景,有两种解决方法可以将 Python 变量传递到 Bash 脚本。

这是我在笔记本中使用 Python3 的示例代码。

  1. 在 Azure Databricks Notebook 的同一 shell session 中通过环境变量传递少量数据,如下所示。

    %python
    import os
    l = ['A', 'B', 'C', 'D']
    os.environ['LIST'] = ' '.join(l)
    print(os.getenv('LIST'))

    %%bash
    for i in $LIST
    do
    echo $i
    done

其工作原理如下图。

enter image description here

  • 通过 Azure Databricks Notebook 当前路径中的文件传递大数据,如下所示。

    %python
    with open('varL.txt', 'w') as f:
    for elem in l:
    f.write(elem+'\n')
    f.close()

    %%bash
    pwd
    ls -lh varL.txt
    echo '=======show content=========='
    cat varL.txt
    echo '=====result of script========'
    for i in $(cat varL.txt)
    do
    echo $i
    done
  • 其工作原理如下图。

    enter image description here

    关于python - 如何将python变量传递给azure databricks笔记本中的shell脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54662605/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com