【问题标题】:Setting Environmental Variables Through a BASH Script in Jupyter在 Jupyter 中通过 BASH 脚本设置环境变量
【发布时间】:2021-04-02 02:42:13
【问题描述】:

我正在尝试执行一个 BASH 脚本,该脚本从 Jupyter 笔记本中设置所需的环境变量。我知道魔术命令 %env 可以做到这一点,但在这种情况下需要 BASH 脚本。使用 !source 或 %system 都无法实现使环境变量在 Jupyter notebook 中持久存在的目标。这个可以吗?

【问题讨论】:

  • 我不清楚您所说的 “persist” 是什么意思。你的意思是他们在重新启动后保持不变?或者他们在不同的笔记本之间保持不变?或者他们从一个单元格到另一个单元格保持不变?请问你想做什么?

标签: bash jupyter-notebook environment-variables


【解决方案1】:

您可以使用 python 来更新 os 变量:

单元格

! echo "export test1=\"This is the test 1\"" > test.sh
! echo "export test2=\"This is the test 2\"" >> test.sh
! cat test.sh

结果

export test1="This is the test 1"
export test2="This is the test 2"

单元格(取自set environment variable in python script

import os

with open('test.sh') as f:
    os.environ.update(
        line.replace('export ', '', 1).strip().split('=', 1) for line in f
        if 'export' in line
)

! echo $test1 
! echo $test2

结果

"This is the test 1"
"This is the test 2"

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 2013-11-15
    • 2016-10-07
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多