Pipe Ipython magic output to a variable?

跟風遠走 提交于 2019-12-01 02:43:53

What about using this:

myvar = !some_command --option1 --option2 foo bar

instead of the %%bash magic? Using the ! symbol runs the following command as a shell command, and the results are all stored in myvar. For running multiple commands and collecting the output of all of them, just put together a quick shell script.

For completeness, if you would still like to use the %%bash cell magic, you can pass the --out and --err flags to redirect the outputs from the stdout and stderr to a variable of your choice.

From the doucumentation:

%%bash --out output --err error
echo "hi, stdout"
echo "hello, stderr" >&2

will store the outputs in the variables output and error so that:

print(error)
print(output)

will print to the python console:

hello, stderr
hi, stdout

Notice the difference in the variable type between @MattDMo (SList) and @oLas (str) answers:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!