IPython 脚本中的 Bash 单元魔法

标签 bash ipython

这是我关于 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/

相关文章:

linux - 如何 grep 文本中的小错误

linux - 从 shell 脚本启动时使 redis 服务器忽略 Ctrl+C

bash - 在 bash 中比较数字时为 “No such file or directory”

tensorflow - 在 Jupyter 中可视化 TensorFlow 图不起作用

ipython - 使用目录将IPython笔记本编写为HTML或PDF

jupyter-notebook - ipywidgets:更改小部件值后自动更新变量并运行代码

php - 通过php和bash执行服务命令

linux - 拆分以分号分隔的单词

python - 如何让 IPython Notebook 运行 Python 3?

python - 从 ipython 导入