+-
如何从Jupyter笔记本上的* .IPYNB文件中执行* .PY文件?
我正在研究 Python笔记本,我希望将大量输入代码[输入]打包成[* .PY]文件并从笔记本中调用这些文件.

我知道从Notebook运行[.PY]文件的操作,并且命令因Linux或Windows而异.但是当我执行此操作并从笔记本执行[.PY]文件时,它无法识别笔记本中加载的任何现有库或变量(就像[.PY]文件从零开始…).

有没有什么办法解决这一问题?

问题的一个可能的简化示例如下:

In[1]:
import numpy as np
import matplotlib.pyplot as plt

In[2]:
def f(x):
    return np.exp(-x ** 2)

In[3]:
x = np.linspace(-1, 3, 100)

In[4]:
%run script.py

“script.py”具有以下内容:

plt.plot(x, f(x))
plt.xlabel("Eje $x$",fontsize=16)
plt.ylabel("$f(x)$",fontsize=16)
plt.title("Funcion $f(x)$")

>在真正的问题中,文件[* .PY]没有4行代码,它有足够的代码.

最佳答案
%run magic documentation你可以找到:

-i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.

因此,提供-i可以解决问题:

%run -i 'script.py'

这是“正确”的方式

也许上面的命令正是你所需要的,但是随着这个问题得到了所有的关注,我决定为那些不知道如何更像pythonic方式的人增加几美分.
上面的解决方案有点hacky,并使另一个文件中的代码混乱(这个x变量来自哪里?f函数是什么?).

我想告诉你如何做到这一点,而不必一次又一次地执行其他文件.
只需将其转换为具有自己的功能和类的模块,然后从您的Jupyter笔记本或控制台导入它.这也具有使其易于重复使用的优点,并且jupyters contextassistant可以帮助您自动完成,或者如果您编写了文档字符串,则会显示文档字符串.
如果您经常编辑其他文件,那么autoreload会帮助您.

您的示例如下所示:
script.py

import matplotlib.pyplot as plt

def myplot(f, x):
    """
    :param f: function to plot
    :type f: callable
    :param x: values for x
    :type x: list or ndarray

    Plots the function f(x).
    """
    # yes, you can pass functions around as if
    # they were ordinary variables (they are)
    plt.plot(x, f(x))
    plt.xlabel("Eje $x$",fontsize=16)
    plt.ylabel("$f(x)$",fontsize=16)
    plt.title("Funcion $f(x)$")

Jupyter控制台

In [1]: import numpy as np

In [2]: %load_ext autoreload

In [3]: %autoreload 1

In [4]: %aimport script

In [5]: def f(x):
      :     return np.exp(-x ** 2)
      :
      :

In [6]: x = np.linspace(-1, 3, 100)

In [7]: script.myplot(f, x)

In [8]: ?script.myplot
Signature: script.myplot(f, x)
Docstring:
:param f: function to plot
:type f: callable
:param x: x values
:type x: list or ndarray
File:      [...]\script.py
Type:      function
点击查看更多相关文章

转载注明原文:如何从Jupyter笔记本上的* .IPYNB文件中执行* .PY文件? - 乐贴网