如何从Jupyter笔记本上的* .IPYNB文件执行* .PY文件? [英] How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

查看:296
本文介绍了如何从Jupyter笔记本上的* .IPYNB文件执行* .PY文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python笔记本,并且希望大输入代码[input] 打包为[* .PY]文件并从笔记本中调用此文件.

I am working on a Python Notebook and I would like that large input code [input] pack into a [* .PY] files and call this files from the notebook.

我知道从Notebook运行[ .PY]文件的操作,该命令在Linux或Windows之间有所不同. 但是当我执行此操作并从笔记本计算机执行[.PY]文件时,它无法识别笔记本计算机中加载的任何现有库或变量(就像[ .PY]文件从零开始...).

The action of running a [.PY] file from the Notebook is known to me and the command varies between Linux or Windows. But when I do this action and execute the [.PY] file from the notebook, it does not recognize any existing library or variable loaded in the notebook (it's like the [.PY] file start from zero...).

有什么办法可以解决这个问题?

Is there any way to fix this?

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

A possible simplified example of the problem would be the following:

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 "具有以下内容:

Where "script.py" has the following content:

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魔术文档,您可以找到:

    In the %run magic documentation you can find:

    -i 在IPython的命名空间而不是空的命名空间中运行文件.如果您正在实验用文本编辑器编写的代码,该代码依赖于交互式定义的变量,则这很有用.

    -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可以解决问题:

    Therefore, supplying -i does the trick:

    %run -i 'script.py'
    


    正确"的方法

    也许上面的命令正是您所需要的,但是在这个问题得到所有关注的情况下,我决定为那些不知道如何使用更pythonic的方式的人再加上几分钱.
    上面的解决方案有点笨拙,并且使另一个文件中的代码令人困惑(此x变量从何而来?f函数是什么?).

    Maybe the command above is just what you need, but with all the attention this question gets, I decided to add a few more cents to it for those who don't know how a more pythonic way would look like.
    The solution above is a little hacky, and makes the code in the other file confusing (Where does this x variable come from? and what is the f function?).

    我想向您展示如何做到这一点,而不必一遍又一遍地执行另一个文件.
    只需将其转换为具有其自身功能和类的模块,然后从Jupyter笔记本电脑或控制台导入即可.这也具有使其易于重用的优点,并且jupyters contextassantant可以帮助您自动完成,或者如果您编写了文档字符串,则可以显示docstring.
    如果您要不断编辑其他文件,请 autoreload 助您一臂之力.

    I'd like to show you how to do it without actually having to execute the other file over and over again.
    Just turn it into a module with its own functions and classes and then import it from your Jupyter notebook or console. This also has the advantage of making it easily reusable and jupyters contextassistant can help you with autocompletion or show you the docstring if you wrote one.
    If you're constantly editing the other file, then autoreload comes to your help.

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

    Your example would look like this:
    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文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆