将Ipython magic输出传输到变量?
我想在ipython笔记本中运行一个bash脚本,并将输出保存为python变量中的字符串,以供进一步操作。基本上,我想通过管道将bash magic的输出传递给一个变量, 例如,类似以下内容的输出:将Ipython magic输出传输到变量?,python,python-2.7,ipython,ipython-notebook,ipython-magic,Python,Python 2.7,Ipython,Ipython Notebook,Ipython Magic,我想在ipython笔记本中运行一个bash脚本,并将输出保存为python变量中的字符串,以供进一步操作。基本上,我想通过管道将bash magic的输出传递给一个变量, 例如,类似以下内容的输出: %%bash some_command [options] foo bar 使用这个怎么样: myvar = !some_command --option1 --option2 foo bar 而不是%%%bash魔法?使用symbol以shell命令的形式运行以下命令,结果都存储在myvar
%%bash
some_command [options] foo bar
使用这个怎么样:
myvar = !some_command --option1 --option2 foo bar
而不是
%%%bash
魔法?使用
symbol以shell命令的形式运行以下命令,结果都存储在myvar
中。要运行多个命令并收集所有命令的输出,只需编写一个快速shell脚本。为了完整起见,如果您仍然想使用%%bash
单元格魔术,您可以传递--out
和--err
标志,将stdout和stderr的输出重定向到您选择的变量
从:
将输出存储在变量输出
和错误
中,以便:
print(error)
print(output)
将打印到python控制台:
hello, stderr
hi, stdout
注意@MattDMo(
SList
)和@oLas(str
)答案之间变量类型的差异:
有可能区分stdout和stderr吗?@Vinayak使用
%%capture
单元格魔法,您可以轻松区分stdout和stderr。见和。看起来与下面oLas的答案相似,但提供了另一条路线。
hello, stderr
hi, stdout
In [1]: output = !whoami
In [2]: type(output)
Out[2]: IPython.utils.text.SList
In [3]: %%bash --out output
...: whoami
In [4]: type(output)
Out[4]: str