4

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?

Community
  • 1
  • 1
Laurent
  • 73
  • 7

2 Answers2

6

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
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • 1
    Great that it helped. BTW, you have the privilege to [upvote](http://stackoverflow.com/help/privileges/vote-up). ;) – Mike Müller Jul 09 '16 at 03:14
  • According to its docs, this 'magic' is deprecated. It recommends `ip.run_line_magic(magic_name, line)` instead. – hpaulj Jul 09 '16 at 05:24
  • @hpaulj Thanks for the pointer. But is still used internally `%pwd`, `_ih[-2]`, `"get_ipython().magic('pwd')"`. – Mike Müller Jul 09 '16 at 05:49
  • In the latest implementation `ip.magic` uses `ip.run_line_magic`, after splitting name from line. But it's certainly possible that haven't rewritten all older uses. – hpaulj Jul 09 '16 at 07:21
0

thank you @Mike for your answer, it pointed me in the right direction for making a cell magic alias

I found that %alias_magic [-l] [-c] [-p PARAMS] name target, in the docs, does the trick for me

in my case:

%alias_magic --cell py_310 script -p C:\Users\myname\AppData\Local\Programs\Python\Python310\python

output

Created `%%py_310` as an alias for `%%script C:\Users\myname\AppData\Local\Programs\Python\Python310\python`.

that can then be used like

%%py_310

import sys

print(sys.version_info)

output

sys.version_info(major=3, minor=10, micro=1, releaselevel='final', serial=0)
lexc
  • 61
  • 3