我可以在"%% bash"或"%% script" ipython笔记本单元中访问python变量吗? [英] Can I access python variables within a `%%bash` or `%%script` ipython notebook cell?

查看:678
本文介绍了我可以在"%% bash"或"%% script" ipython笔记本单元中访问python变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从%%bash或其他%%script单元中访问当前python内核中的变量?

Is there a way to access variables in the current python kernel from within a %%bash or other %%script cell?

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

Perhaps as command line arguments or environment variable(s)?

推荐答案

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

Python variables can be accessed in the first line of a %%bash or %%script cell, and so can be passed as command line parameters to the script. For example, with bash you can do this:

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

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

The -s command line option allows you to pass positional parameters to bash, accessed through $n for the n-th positional parameter. Note that what's actually assigned to the bash positional variable is the result of str(myPythonVariable). If you're passing strings containing quote characters (or other bash-sensitive characters), you'll need to escape them with a backslash (eg: \").

引号很重要-如果没有引号,则python变量(字符串表示形式)会在空格上分开,因此如果myPythonVardatetime.datetimestr(myPythonVar)"2013-10-30 05:04:09.797507"的话,则上述bash脚本将收到3个位置变量,前两个值分别为2013-10-3005:04:09.797507.输出为:

The quotes are important - without them the python variables (string representations) are split on spaces, so if myPythonVar was a datetime.datetime with str(myPythonVar) as "2013-10-30 05:04:09.797507", the above bash script would receive 3 positional variables, the first two with values 2013-10-30 and 05:04:09.797507. It's output would be:

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

如果您要命名变量并且您正在运行linux,请采用以下方法:

If you want to name the variables and you're running linux, here's an approach:

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

您可以指定多个变量分配.再次提防引号和其他类似的东西(在这里bash会痛苦地抱怨!).要了解为什么这行得通,请参见env手册页.

You can specify multiple variable assignments. Again beware of quotes and other such things (here bash will complain bitterly!). To grok why this works, see the env man page.

这篇关于我可以在"%% bash"或"%% script" ipython笔记本单元中访问python变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆