pythonipython

%reset in script only if run through iPython?


I'm developing some code in Spyder on local machine. This code need to be run on a remote server through python directly.

While developing in Spyder, I used to put a %reset -f at the very beginning in order to clear all the variables (something similar to the so-called "clearvars" or "clear all" in Matlab interactive session).

But this command in pure Python has no meaning and will raise an error

$ python prepare_data.py
  File "/home/donut/code/prepare_data.py", line 8
    %reset -f
    ^
SyntaxError: invalid syntax

I would like to write something like: "if run through iPython then execute %reset -f", but are there other solutions?

I read Ignore IPython magic in python and the main answer was to pipe the whole script into a grep function in order to remove all the magic commands prior to sending it to Python. I understand that this will do the jobs, but it's a little ugly and perhaps some solutions have been introduced since?


Solution

  • from IPython.core import getipython
    ipython = getipython.get_ipython()
    if ipython:
        ipython.run_line_magic("reset", "-f")
    

    Tested with Python 3.12.0 and IPython 8.22.1