如何从 Jupyter 笔记本上的 * .IPYNB 文件执行 * .PY 文件?

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

我正在 Python 笔记本上工作,我希望 大输入代码 [input] 打包成 [* .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)$")

也许不是很优雅,但它完成了工作:

exec(open("script.py").read())

%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'

"correct" 方法

也许上面的命令正是您所需要的,但是考虑到这个问题得到的所有关注,我决定为那些不知道更 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

下面几行也可以

!python script.py

!python 'script.py'

将 script.py 替换为您的真实文件名,不要忘记 ''

也可以通过使用 %run 魔术调用模块来完成相同的操作,如下所示:

%run -m script

其中 -m 是您的模块,即 script.py 但仅使用它提供 script 也可以完成工作。