2

I'd like to pass variables I've defined in iPython into a python script.

For example:

In [1]: import demo
In [2]: x = [1, 2, 3]
In [3]: y = [1, 2, 3]
In [4]: rtp x y

Where the script is:

import IPython.ipapi
ip = IPython.ipapi.get()

def run_this_plot(*args):
    """ Run
    Examples
    In [1]: import demo
    In [2]: rtp x y <z> 
    Where x, y, and z are numbers of any type
    """
    print "args: ", args
    # Do something here with args, such as plot them

# Activate the extension
ip.expose_magic("rtp", run_this_plot)

So I'd like the values from x and y in iPython, whatever they might be (ints, ranges, etc) to be seen from the script, which right now only sees the string "x y".

How might I obtain these values in the transfer from iPython to a script? If it's not possible, what do people usually do as a workaround?

Thanks! --Erin

2 Answers 2

1

You might find it useful to browse the source of the IPython.Magic module for clues. It would appear you can only get one string argument into a custom magic method. But I can't seem to find a doc reference to confirm.

While I imagine there's a better way to accomplish this, the following should work for your specific example:

import IPython.ipapi
ip = IPython.ipapi.get()

def run_this_plot(self, arg_s=''):
    """ Run
    Examples
    In [1]: import demo
    In [2]: rtp x y <z> 
    Where x, y, and z are numbers of any type
    """
    args = []
    for arg in arg_s.split():
        try:
            args.append(self.shell.user_ns[arg])
        except KeyError:
            raise ValueError("Invalid argument: %r" % arg)
    print "args: ", args
    # Do something here with args, such as plot them

# Activate the extension
ip.expose_magic("rtp", run_this_plot)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you- this is exactly what I was looking for. With x and y values set, rtp x y now prints the correct values.
0

It worked fine when I did

rtp x, y

2 Comments

That's strange. I still get a string output- 'x, y' when I use that line. Does python recognize the correct types of your x, y variables as well?
I'm using Python 2.7 and iPython 0.10.1 Win 32.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.