7

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?

7
  • 1
    After %load_ext autoreload can you tab-complete %autoreload? Commented Oct 2, 2015 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. Commented Oct 2, 2015 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. Commented Oct 2, 2015 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). Commented Oct 2, 2015 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. Commented Oct 3, 2015 at 11:57

1 Answer 1

10

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') 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this! You could even put the first two lines of code inside the if statement for better encapsulation.
ipython.magic is now deprecated, use run_line_magic instead

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.