sjk*_*sjk 3 python emacs bash shell ipython
这是我在 SO 上的第一篇文章,所以如果我做错了什么,请告诉我。
我对在 ipython 中使用不同的编程语言很感兴趣,类似于 emacs 组织模式下的 babel/literal 编程。我喜欢 emacs 组织模式的一点是,可以有多个“单元”连接到同一个 R/bash 会话。这允许我重用在文档的较早部分创建的变量/函数,即使我在两者之间做了其他事情。
我发现这在带有 Rmagic 的 ipython 中是可能的。举个例子
In [1]: %load_ext rpy2.ipython
In [2]: %%R
a <- 3
a
Out [2]: 3
In [3]: something_in_python = 'I am doing something unrelated now'
In [4]: %%R
cat('My variable a is still here, its value is: ', a) # a is still here!
Out [4]: My variable is still here, its value is: 3
Run Code Online (Sandbox Code Playgroud)
我非常希望能够在 bash 中做类似的事情。但是,无论我使用“%%script bash”还是 %%sx,变量都不是持久的。这是我想要做的:
In [1]: %%script bash
var1="hello"
echo $var1
Out[1]: hello
In [2]: %%script bash
echo $var1 # I need $var1 to be present in this cell too - but its gone!
Out[62]:
Run Code Online (Sandbox Code Playgroud)
无论如何在多个单元格中有相同的基本会话吗?或者至少以某种方式传递变量。当然,我可以尝试将变量传递到 python 中,然后再返回到下一个 bash 单元,但我觉得一定有更好的方法。感谢您的帮助!
PS:我寻找了一个解决方案,但我在这里或通过谷歌搜索都没有找到任何东西。有一些这样的东西:IPython Notebook previous cell content,但它似乎对我的情况没有帮助。
小智 5
One option, though limited, allows the stdout and stderr variables to be set. This gives you the availability of setting and passing two variables in between cells. For example:
In [1]:%%bash --out var1 --err var2
echo "Hello"
echo "Hi" >&2
In [2]:print(var1)
print(var2)
# Resulting in:
Hello
Hi
In [3]:%%bash -s "$var1" "$var2"
echo "arg1 takes on var1 = $1"
echo "arg2 takes on var2 = $2"
# Resulting in:
arg1 takes on var1 = Hello
arg2 takes on var2 = Hi
Run Code Online (Sandbox Code Playgroud)
Note that the eol character seems to make its way into the variable.
有关使用 stdout 和 stderr 的详细信息,请参阅http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/IPython%20Kernel/Script%20Magics.ipynb
有关将变量传回的详细信息,请参阅我可以访问 `%%bash` 或 `%%script` ipython notebook 单元中的 python 变量吗?