python - 无法执行通过%paste%指定的函数

标签 python ipython ipython-magic

是否可以运行 IPython 中使用神奇的 %paste% 函数指定的函数?

In [1]: %paste%
def add_to_index(index,keyword,url):
    for e in index:
        if e[0] == keyword:
            if url not in e[1]:
                e[1].append(url)
            return
    index.append([keyword,[url]])

## -- End pasted text --
Block assigned to '%'

In [2]: %whos
Variable   Type     Data/Info
-----------------------------
%          SList    ['def add_to_index(index,<...>append([keyword,[url]])']

In [3]: add_to_index
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-e3075a18cb0c> in <module>()
----> 1 add_to_index

NameError: name 'add_to_index' is not defined

In [4]: add_to_index(index, 'test', 'http://test.com')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-580237464b17> in <module>()
----> 1 add_to_index(index, 'test', 'http://test.com')

NameError: name 'add_to_index' is not defined

In [5]:

最佳答案

粘贴魔法是%paste(没有尾随%):

In [3]: %paste
def add_to_index(index,keyword,url):
    for e in index:
        if e[0] == keyword:
            if url not in e[1]:
                e[1].append(url)
            return
    index.append([keyword,[url]])
## -- End pasted text --

In [4]: add_to_index
Out[4]: <function __main__.add_to_index>

在您的情况下,您正在使用 %paste 的可选参数:

In [5]: %paste?
Type:       Magic function

...(text omitted)

You can also pass a variable name as an argument, e.g. '%paste foo'.
This assigns the pasted block to variable 'foo' as string, without
dedenting or executing it (preceding >>> and + is still stripped)

当您这样做时,粘贴的代码不会被执行,它只是分配给您作为参数提供的变量(在您的情况下为 % )。

关于python - 无法执行通过%paste%指定的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12571294/

相关文章:

python - Canvas 上的 Kivy 插值

python - 执行、闭包和作用域

python - 对 Pandas DataFrame 中存在非数字值的所有列求和

python - IPython笔记本安装错误

python - Cython ipython 魔术与编译时环境变量

python - Bottle python 中的 Rebase 模板函数不会按应有的方式呈现模板

python - 使用python访问if循环中的变量值

python - 将 jupyter 笔记本 (ipython) 集成到组织模式笔记本中

ipython - 如何在 ipdb 上的 iPython 笔记本中自动完成?

python - IPython Cell Magic 在客户端和所有引擎中运行这个单元