gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:20 25 4
gpt4 key购买 nike

我想将我在 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)

关于python - 在脚本中使用 iPython 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6928102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com