Use variables from iPython in a script
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开发者_C百科 not possible, what do people usually do as a workaround?
Thanks! --Erin
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)
It worked fine when I did
rtp x, y
精彩评论