gpt4 book ai didi

jupyter-notebook - 我可以访问 `%%bash` 或 `%%script` ipython 笔记本单元中的 python 变量吗?

转载 作者:行者123 更新时间:2023-12-03 06:01:38 25 4
gpt4 key购买 nike

有没有办法从 %%bash 或其他 %%script 单元中访问当前 python 内核中的变量?

也许作为命令行参数或环境变量?

最佳答案

Python 变量可以在 %%bash%%script 单元格的第一行中访问,因此可以作为命令行参数传递给脚本。例如,使用 bash,您可以执行以下操作:

%%bash -s "$myPythonVar" "$myOtherVar"
echo "This bash script knows about $1 and $2"

-s 命令行选项允许您将位置参数传递给 bash,通过 $n 访问第 n 个位置参数。请注意,实际分配给 bash 位置变量的是 str(myPythonVariable) 的结果。如果您传递包含引号字符(或其他 bash 敏感字符)的字符串,则需要使用反斜杠对其进行转义(例如:\")。

引号很重要 - 没有它们,python 变量(字符串表示形式)将按空格分割,因此如果 myPythonVardatetime.datetimestr( myPythonVar)"2013-10-30 05:04:09.797507",上面的 bash 脚本将接收 3 个位置变量,前两个值为 2013-10-30 05:04:09.797507。它的输出将是:

This bash script knows about 2013-10-30 and 05:04:09.797507

如果您想命名变量并且运行的是 Linux,则有一种方法:

%%script env my_bash_variable="$myPythonVariable" bash
echo myPythonVariable\'s value is $my_bash_variable

您可以指定多个变量赋值。再次提防引号和其他类似的东西(这里 bash 会大声提示!)。要了解其工作原理,请参阅 env 手册页。

关于jupyter-notebook - 我可以访问 `%%bash` 或 `%%script` ipython 笔记本单元中的 python 变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579546/

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