> ## Documentation Index
> Fetch the complete documentation index at: https://ayakaleaf-pro.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Runner

> 在项目中运行 Python 脚本，并保存它写出的内容，例如用于文档的图表。

Python 脚本在你的浏览器中运行，因此输出会直接显示在编辑器下方。无需任何设置。

**1. 创建脚本**

在文件树中，点击 **New file** 图标。输入以 `.py` 结尾的名称，然后点击 **Create**。

![名称为 analysis.py 的 Add Files 对话框](https://mintcdn.com/ayakaleaf-pro/PeD9iteXIf8j4GXw/images/on-premises/python-runner-new-file.png?fit=max\&auto=format\&n=PeD9iteXIf8j4GXw\&q=85\&s=6be49974e488f7678604cc0644f43bdc)

新的 Python 文件

编辑器下方会出现 **Run** 按钮和输出窗格。第一次使用时，在 Python 加载期间该按钮保持禁用状态。

**2. 运行脚本**

编写代码并点击 **Run**。脚本打印的内容会显示在输出窗格中。无需先保存。

脚本写出的文件会保存到你的项目中。一条消息会告诉你是哪个文件，例如 **results.txt saved to your project**，该文件也会出现在文件树中。

![编辑器中的脚本、下方打印的输出，以及消息 results.txt saved to your project](https://mintcdn.com/ayakaleaf-pro/PeD9iteXIf8j4GXw/images/on-premises/python-runner-output.png?fit=max\&auto=format\&n=PeD9iteXIf8j4GXw\&q=85\&s=28188ffe214aedd1203d2734891917f7)

输出和已保存的文件

**3. 停止脚本**

脚本运行时，**Run** 会变成 **Stop**。点击它即可中断脚本。输出窗格以 **Execution interrupted** 结尾。

![Stop 按钮和正在运行的脚本的输出](https://mintcdn.com/ayakaleaf-pro/PeD9iteXIf8j4GXw/images/on-premises/python-runner-stop.png?fit=max\&auto=format\&n=PeD9iteXIf8j4GXw\&q=85\&s=263af195efa53538f1e3b37b4fad6041)

正在运行的脚本

## 在文档中使用图表

绘图没有可以显示的窗口，因此请将其保存到文件中。例如：

```python theme={null}
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig("figure.png")
```

`figure.png` 会出现在你的项目中，可直接用于 `\includegraphics{figure.png}`。

![在编辑器中打开的 figure.png，以及消息 figure.png saved to your project](https://mintcdn.com/ayakaleaf-pro/PeD9iteXIf8j4GXw/images/on-premises/python-runner-figure.png?fit=max\&auto=format\&n=PeD9iteXIf8j4GXw\&q=85\&s=8b0074f8d46a40a105a459a6c09caabf)

已保存的绘图

## 读取项目中的文件

脚本可以按路径打开项目中的文件：

```python theme={null}
print(open("results.txt").read())
```

## 出现问题时

**脚本引发错误。**错误会以红色显示在输出窗格中，位于脚本此前打印的所有内容之后。

![打印的文本后跟一段红色的 traceback](https://mintcdn.com/ayakaleaf-pro/PeD9iteXIf8j4GXw/images/on-premises/python-runner-error.png?fit=max\&auto=format\&n=PeD9iteXIf8j4GXw\&q=85\&s=89ef60d790737fe01d6d69b1e0395e9e)

脚本中的错误

**`ModuleNotFoundError: No module named ...`。**只能使用 Pyodide 内置的软件包，无法使用通过 `pip` 安装的软件包。NumPy 和 Matplotlib 都在可用之列，该消息还会链接到[完整列表](https://pyodide.org/en/stable/usage/packages-in-pyodide.html)。

![输出窗格中的 ModuleNotFoundError](https://mintcdn.com/ayakaleaf-pro/PeD9iteXIf8j4GXw/images/on-premises/python-runner-missing-package.png?fit=max\&auto=format\&n=PeD9iteXIf8j4GXw\&q=85\&s=5dbbfca95ee2b6984e2b3220e500231a)

不可用的软件包


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.