Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore IPython magic in python

What is the best way to ignore IPython magic when running scripts using the python interpreter?

I often include IPython magic in my script files because it work with the code interactively. For example, with the autoreload magic, I don't have to keep reload-ing the modules after I make some changes and fix bugs:

%load_ext autoreload
%autoreload 2

However, when I try to run this script using a usual python interpreter, I get an error:

  File "<string>", line 1
    %load_ext autoreload
    ^
SyntaxError: invalid syntax

Wrapping IPython magic inside an if statement does not work, because incorrect syntax is detected before the file is actually ran.


So what is the best way to get python to ignore IPython magic?

It's annoying to have to change your scripts whenever you want to run then in python, pdb, sphinx, etc.

like image 274
ostrokach Avatar asked Sep 25 '26 20:09

ostrokach


1 Answers

For all tools that can read from standard input you could use grep to remove any magic lines and pipe the result into python:

grep -v '^%' magicscript.ipy | python

Works well as a bash alias:

alias pynomagic='( grep -v "^%" | python ) < '
pynomagic magicscript.ipy

Tools like pdb that only accept filenames could be called like this (bash again):

pdb <(grep -v '^%' magicscript.ipy)
like image 200
dmaticzka Avatar answered Sep 28 '26 10:09

dmaticzka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!