7

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?

3 Answers 3

9

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

%%bash ls 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, what made it work is the newline between the %%bash magic to the actual command(s).
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.

1 Comment

I guess I didn't read that post well enough. Will keep this in mind. gmk's suggestion seems to work.
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.