pythonipythonipython-magic

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 the sys.argv list:

In [1]: import sys
In [2]: run -i test.py random args
['test.py', '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?


Solution

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

    from IPython.core.magic import register_line_magic
    
    @register_line_magic
    def r(line):
        get_ipython().magic('run -i ' + line)
    
    del r
    

    EDIT

    As hpaulj points out magic is deprecated. Here a version with the new run_line_magic:

    from IPython.core.magic import register_line_magic
    
    @register_line_magic
    def r(line):
        get_ipython().run_line_magic('run', ' -i ' + line)
    
    del r
    Now:
    
    %r
    

    does the same as:

    %run -i