6

I am trying to include some of the IPython built-in magic functions to auto reload modules when I am running a script. So I have tried this:

if __IPYTHON__:
    %load_ext autoreload
    %autoreload 2

But IPython returns:

%load_ext autoreload
^
SyntaxError: invalid syntax

Any idea how to solve this?

Nick T
  • 24,120
  • 11
  • 77
  • 117
Jemme
  • 183
  • 1
  • 10
  • 1
    After `%load_ext autoreload` can you tab-complete `%autoreload`? – colidyre Oct 02 '15 at 12:12
  • Another try could be to edit your ipython_config.py with `c.InteractiveShellApp.extensions = ['autoreload']` and `c.InteractiveShellApp.exec_lines = ['%autoreload 2']`. This could not help, but it's worth a try. – colidyre Oct 02 '15 at 12:16
  • @colidyre What do you mean by tab-complete?. Also I don't want to change the ipython_config.py because I want to implement this only on certain scripts, not all of them. – Jemme Oct 02 '15 at 12:42
  • Tab completion is just e.g. to exclude non printable characters accidentally put in your console or to exclude import errors. You just type `%` and then press tabulator key. Then you should see (there is a chance that you don't have this feature) a list of possible commands. This is very basic and also very fast to check. You can also provide some version information (python and iPython). – colidyre Oct 02 '15 at 13:06
  • @colidyre, I thought you were referring to something different. I know for sure both lines are fine because I can execute them directly in iPython, but when I include them on the script and run them from there, I get that error. It seems a problem with trying to use magic functions from a script. – Jemme Oct 03 '15 at 11:57
  • Ok. You've written _when I am working interactively_. This is misleading. I recommend to correct that in your question to clarify this behaviour happens in execution of a script. – colidyre Oct 03 '15 at 12:01
  • Ok, I edited the text. Hope it makes more sense now. – Jemme Oct 06 '15 at 12:07
  • 2
    Possible duplicate of [How to run an IPython magic from a script (or timing a Python script)](http://stackoverflow.com/questions/10361206/how-to-run-an-ipython-magic-from-a-script-or-timing-a-python-script) – Gall Oct 06 '15 at 12:28

1 Answers1

9

Thank you for the link Gall!!! Whit your help I came up with the following solution:

from IPython import get_ipython
ipython = get_ipython()

if '__IPYTHON__' in globals():
    ipython.magic('load_ext autoreload')
    ipython.magic('autoreload 2')
Jemme
  • 183
  • 1
  • 10
  • Thanks for this! You could even put the first two lines of code inside the if statement for better encapsulation. – zanbri May 18 '16 at 17:46