在VSCode中将.ipynb转换为.py的最佳方法

2024-09-26 19:30:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种在VSCode中将.ipynb转换为.py文件的好方法。到目前为止,我已经尝试:

  • vscode中内置的“导出为”选项。不理想,因为它在脚本开始时会生成以下内容,以及“运行单元格”、“在下面运行”等按钮/链接:

"To add a new cell, type '# %%' To add a new markdown cell, type '# %% [markdown]' %% from IPython import get_ipython"

  • nbconvert。我通常将其作为命令插入脚本本身(https://stackoverflow.com/a/19779226/14198216),以便在运行时自动转换和保存。但这也会留下“运行单元”等,以及执行标记(例如:“In[1]”)

  • jupytext。我通常也会将其作为命令插入。在.py的开头,它生成:

-- coding: utf-8 -- --- jupyter: jupytext: text_representation:

有没有一个好的、极简主义的解决方案,它不会在我的笔记本的.py版本中插入一堆乱七八糟的东西(需要手动编辑),并且可以从笔记本本身轻松/自动执行?这也可能是设置一些我目前还不知道的调整,可以使我提到的其中一项工作做得更好

提前谢谢


Tags: 文件topy命令脚本addnewtype
2条回答

我们可以在“settings.json”中添加以下设置,生成的python文件将不会有“运行单元格”、“运行在上面”、“调试单元格”:

"jupyter.codeLenses": " ",

enter image description here

我发现有一种方法可以直接在VS代码中导出:

https://code.visualstudio.com/docs/python/jupyter-support-py

Export a Jupyter notebook

In addition to opening a Jupyter notebook, you can also use one of the following commands from the Command Palette (⇧⌘P) to export content from a Python file in VS Code to a Jupyter notebook (with the .ipynb extension).

  • Jupyter: Export Current Python File as Jupyter Notebook: creates a Jupyter notebook from the contents of the current file, using the # %% and # %% [markdown] delimiters to specify their respective cell types.
  • Jupyter: Export Current Python File and Output as Jupyter Notebook: creates a Jupyter notebook from the contents of the current file and includes output from code cells.
  • Jupyter: Export Interactive Window as Jupyter Notebook: creates a Jupyter notebook from the contents of the Python Interactive window.

After exporting the contents, VS Code displays a prompt through which you can open the notebook in a browser.

相关问题 更多 >

    热门问题