5

This is my first post on SO, so please let me know if the problem is not well defined. I have a script process.ipy in which I am trying to implement a cell magic as follows,

#!/usr/bin/env ipython

%%bash
ls

When I run this on the command line (Ubuntu and zsh shell), I get the following error,

$ ipython process.ipy                                                                                                 
File "<ipython-input-1-f108be8d32f2>", line 3
  %%bash
  ^
SyntaxError: invalid syntax

However, I can run this in the ipython session without a problem,

In [1]: %%bash
   ...: ls
   ...: 
process.ipy

More confusing, is that the single line version works in the script,

#!/usr/bin/env ipython

!ls

What am I doing wrong? Is something not setup correctly?

pacificprince
  • 53
  • 2
  • 5

3 Answers3

5

Short Answer: magic commands are understood only in an IPython interactive session, not in scripts.

Longer Answer: they can be called in scripts, but only using a library call, not the %% notation as described in How to run an IPython magic from a script (or timing a Python script). Note that the mechanism is IPython version dependent.

Community
  • 1
  • 1
msw
  • 42,753
  • 9
  • 87
  • 112
3

You do not need the #!/usr/bin/env ipython line at the top. The error :

%%bash
ls
magic-sudo
  • 1,206
  • 9
  • 15
1

You do not need the #!/usr/bin/env ipython line at the top. The cell magic should be first line in the cell.

just try the following and it should work

%%bash
ls
Amit
  • 19,780
  • 6
  • 46
  • 54