Skip to content

running_external_code

虽然 Notebook(笔记本)非常适合交互式开发,但你经常需要运行存储在单独 Python 文件(.py)中的代码。IPython 提供了魔术命令(magic commands)来执行外部脚本或将其内容直接加载到你的会话(session)中。

%run 魔术命令用于执行 Python 脚本文件。关键在于,脚本会在与你的 IPython 会话*相同的命名空间(namespace)*中运行。这意味着脚本中定义的任何变量、函数或类在脚本运行完成后都可以在你的交互式会话中访问。

首先,我们创建一个名为 utils.py 的简单 Python 脚本:

%%writefile utils.py
SCRIPT_MESSAGE = "This message comes from utils.py"
def helper_function(x):
print(f"Helper function called with: {x}")
return x * x
print("Executing utils.py...")
result_from_script = helper_function(5)
print("utils.py finished.")

现在,让我们从 IPython 单元格中运行这个脚本:

In [1]: %run utils.py
# Output:
# Executing utils.py...
# Helper function called with: 5
# utils.py finished.

运行脚本后,其中定义的变量和函数在当前会话中是可访问的:

In [2]: print(SCRIPT_MESSAGE)
# Output: This message comes from utils.py
In [3]: print(result_from_script)
# Output: 25
In [4]: helper_function(10)
# Output:
# Helper function called with: 10
Out[4]: 100

你可以像在命令行中一样向脚本传递参数:

# Create script `arg_script.py`
%%writefile arg_script.py
import sys
print(f"Script name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")
# Run with arguments
%run arg_script.py arg1 100 --option

%run 魔术命令还有一些选项,例如 -i,它会运行脚本,然后让你进入脚本命名空间内的 IPython 提示符(这对于调试很有用)。

有时你不想直接执行脚本,而是希望将其代码加载到 Notebook 单元格中,以便运行前进行检查或修改。%load 魔术命令正是为此而生。

# Cell 1:
%load utils.py

执行上述单元格后,其内容将被 utils.py 的内容替换,并在顶部注释掉原始的 %load 命令:

# Cell 1 (after executing %load):
# %load utils.py
SCRIPT_MESSAGE = "This message comes from utils.py"
def helper_function(x):
print(f"Helper function called with: {x}")
return x * x
print("Executing utils.py...")
result_from_script = helper_function(5)
print("utils.py finished.")

现在你可以直接在单元格中编辑这段代码,然后执行它(例如,使用 Shift+Enter),就像你自己输入的一样。

%load 还可以从 URL 或历史记录中的特定行加载代码(例如,%load -r 1-5 从输入历史记录中加载第 1 到 5 行)。

  • %run:立即在当前命名空间中执行脚本。适用于运行工具脚本或主应用程序入口点。
  • %load:将脚本内容插入到单元格中,以便稍后编辑/执行。适用于引入需要修改的示例或代码片段。

注意:较旧的 %edit 魔术命令(用于打开外部编辑器)现在通常不如直接在 JupyterLab 的编辑器中编辑文件或使用 %load 后在单元格中编辑代码常见。