是否可以生成一个jupyter-notebook的可执行文件(.exe)?

15

我用Jupyter Notebook编写了一个Python代码,现在我想生成程序的可执行文件。

2个回答

19

不过,可以从 .ipynb 生成一个 .py 脚本,然后将其转换为 .exe。

使用 jupyter nbconvert 进行转换(如果您使用的是 Anaconda,则已包含此功能)。

在环境中执行:

pip install nbconvert
jupyter nbconvert --to script my_notebook.ipynb

将生成一个my_notebook.py

然后使用Pyinstaller

pip install pyinstaller
pyinstaller my_notebook.py

现在您的文件夹中应该有一个my_notebook.exe和dist文件。

来源:关于此事的略有过时的Medium文章


1
使用pandas时,pyinstaller存在一些陷阱。我在这里编写了一个详细的逐步教程,说明如何创建一个单文件可执行程序(.py -> .exe):https://geo.rocks/post/python-to-exe/。 - do-me

12
您可以使用我编写的代码将大量的.ipynb文件转换为.py文件。
srcFolder = r'input_folderpath_here'
desFolder = r'output_folderpath_here'

import os
import nbformat
from nbconvert import PythonExporter

def convertNotebook(notebookPath, modulePath):
    with open(notebookPath) as fh:
        nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)
    exporter = PythonExporter()
    source, meta = exporter.from_notebook_node(nb)
    with open(modulePath, 'w+') as fh:
        fh.writelines(source)

# For folder creation if doesn't exist
if not os.path.exists(desFolder):
    os.makedirs(desFolder)

for file in os.listdir(srcFolder):
    if os.path.isdir(srcFolder + '\\' + file):
        continue
    if ".ipynb" in file:
        convertNotebook(srcFolder + '\\' + file, desFolder + '\\' + file[:-5] + "py")

将您的.ipynb文件转换为.py文件后,
请尝试运行.py文件以确保它们正常工作。 之后,在终端或命令提示符中使用Pyinstaller。 cd到您的.py文件位置。 然后输入

pyinstaller --onefile yourfile.py

这将生成一个单独的.exe程序文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接