在脚本中使用iPython中的变量

在脚本中使用iPython中的变量,python,ipython,Python,Ipython,我想将我在iPython中定义的变量传递到python脚本中 例如: In [1]: import demo In [2]: x = [1, 2, 3] In [3]: y = [1, 2, 3] In [4]: rtp x y 其中脚本是: import IPython.ipapi ip = IPython.ipapi.get() def run_this_plot(*args): """ Run Examples In [1]: import demo I

我想将我在iPython中定义的变量传递到python脚本中

例如:

In [1]: import demo
In [2]: x = [1, 2, 3]
In [3]: y = [1, 2, 3]
In [4]: rtp x y
其中脚本是:

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)
导入IPython.ipapi
ip=IPython.ipapi.get()
def运行此图(*args):
“跑
例子
在[1]中:导入演示
In[2]:rtp x y
其中x、y和z是任何类型的数字
"""
打印“args:”,args
#在这里使用args执行一些操作,例如绘制它们
#激活分机
ip.expose_magic(“rtp”,运行此图)
因此,我希望在iPython中的x和y的值,无论它们是什么(int、ranges等),都可以从脚本中看到,它现在只看到字符串“xy”

在从iPython到脚本的传输中,我如何获得这些值?如果不可能,人们通常会做些什么作为解决办法

谢谢!
--艾琳

我这样做的时候效果很好

rtp x, y

您可能会发现浏览IPython.Magic模块的链接以寻找线索很有用。看起来您只能将一个字符串参数放入自定义的magic方法中。但我似乎找不到一份证明文件来确认

虽然我认为有更好的方法来实现这一点,但以下应该适用于您的具体示例:

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)
导入IPython.ipapi
ip=IPython.ipapi.get()
def run_此_图(self,arg_s=''):
“跑
例子
在[1]中:导入演示
In[2]:rtp x y
其中x、y和z是任何类型的数字
"""
args=[]
对于参数拆分()中的参数:
尝试:
args.append(self.shell.user\u ns[arg])
除KeyError外:
raise VALUERROR(“无效参数:%r”%arg)
打印“args:”,args
#在这里使用args执行一些操作,例如绘制它们
#激活分机
ip.expose_magic(“rtp”,运行此图)

真奇怪。当我使用该行时,仍然会得到一个字符串输出-'x,y'。python是否也能识别x、y变量的正确类型?我使用的是python 2.7和iPython 0.10.1 Win 32。谢谢,这正是我想要的。设置了x和y值后,rtp x y现在将打印正确的值。