Laurent Laurent - 7 months ago 27
Python Question

IPython run magic: How create an alias for "run -i"?

I am programming a python user interface to control various instruments in a lab. If a script is not run interactively, the connection with instruments is lost at the end of the script, which can be very bad. I want to help the user to 'remember' running the script interactively.

I'm thinking of two possible ways to do it. First, as specified in the title, I could make an alias for run -i:

%alias_magic lab_run run -i

but this returns an error:

UsageError: unrecognized arguments: -i

Is there a way to get around this?

Alternatively, I could detect inside the script if the -i flag was passed on and raise en error if not. However, it doesn't show up in sys.argv list:

In [1]: import sys
In [2]: run -i random args
['', 'random', 'args']

I can't use ipy files, because I need to read %run flags, as explained in my previous question here:
How to add a custom flag to IPython's magic commands? (.ipy files)

Anyone sees a solution to this problem?


You can define your own magic function and use %run -i in it:

from IPython.core.magic import register_line_magic

def r(line):
    get_ipython().magic('run -i ' + line)

del r



does the same as:

%run -i