如何为IPython(notebook)shell命令提供内联输入? [英] How do I provide inline input to an IPython (notebook) shell command?
问题描述
我想把一个带有一些shell命令及其输入的IPython笔记本放在一起。在bash提示符中,我可以使用here-document语法:
I want to put together an IPython notebook with some shell commands and their input. In the bash prompt I can use "here-document" syntax:
bash-3.2$ mysql -u root <<END_IPUT
> use mydb;
> show tables;
> END_INPUT
如何在IPython中获得相同的效果,特别是在jupyter笔记本中?我知道如何执行shell命令作为IPython作为line magics或cell
magics,例如:
How do I get the same effect in IPython, and specifically in a jupyter notebook? I know how to execute shell commands as IPython as "line magics" or "cell magics", e.g.:
In [7]: !! ls -tF
Out[7]: ['Demo-notebook.ipynb',
'createdb.sql',
...
我看过 IPython作为系统shell ,展示了如何启用一些语法细节。在以下之后,我可以运行系统命令而无需预先!
或 !!
I've looked at IPython as a system shell, which shows how to enable some syntactic niceties. After the following, I can run system commands without prepending !
or !!
# Turn everything in $PATH into an alias;
# then enable calling aliases without ! or %
%rehashx
%autocall 2
但这些都没有帮助为内联的这些命令提供输入:here-document语法在IPython中无效,并导致python SyntaxError
。那么我该怎么做呢?
But none of this helps with providing input to these commands inline: The here-document syntax is invalid in IPython, and results in a python SyntaxError
. So how do I do it?
推荐答案
bash cell magic允许你输入多行bash。只需使用 %% bash
启动任何单元格:
The bash cell magic allows you to enter multiple lines of bash. Just start any cell with %%bash
:
%%bash
echo "This is bash"
ls
如果你正在使用heredoc要将文本管道传输到另一个程序,您还可以使用脚本单元格魔术:
If you're using a heredoc to pipe text into another program, you can also use the script cell magic:
%%script bc
2+3
可能还有其他细胞魔法可以更具体地解决您的问题!
There may also be other cell magics which address your problem more specifically!
这篇关于如何为IPython(notebook)shell命令提供内联输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!