这是我关于 SO 的第一篇文章,所以如果问题没有明确定义,请告诉我。我有一个脚本 process.ipy,我在其中尝试如下实现单元魔术,
#!/usr/bin/env ipython
%%bash
ls
当我在命令行(Ubuntu 和 zsh shell)上运行它时,出现以下错误,
$ ipython process.ipy
File "<ipython-input-1-f108be8d32f2>", line 3
%%bash
^
SyntaxError: invalid syntax
但是,我可以在 ipython session 中毫无问题地运行它,
In [1]: %%bash
...: ls
...:
process.ipy
更令人困惑的是,单行版本在脚本中有效,
#!/usr/bin/env ipython
!ls
我做错了什么?是不是设置不正确?
最佳答案
简短回答:只有在 IPython 交互式 session 中才能理解魔术命令,而不能在脚本中理解。
更长的答案:它们可以在脚本中调用,但只能使用库调用,而不是 How to run an IPython magic from a script (or timing a Python script) 中描述的 %%
符号.请注意,该机制取决于 IPython 版本。
关于IPython 脚本中的 Bash 单元魔法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27951206/