Skip to main content
 首页 » 编程设计

python之在脚本中使用 iPython 中的变量

2025年05月04日10mayingbao

我想将我在 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 中的 x 和 y 的值,无论它们可能是什么(整数、范围等)都可以从脚本中看到,现在只能看到字符串“x y”。

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

谢谢! --艾琳

请您参考如下方法:

您可能会发现浏览 source 很有用IPython.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)