失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python的notebook怎么用_如何通过命令行将IPython Notebook转换为Python文件?

python的notebook怎么用_如何通过命令行将IPython Notebook转换为Python文件?

时间:2023-06-18 01:53:26

相关推荐

python的notebook怎么用_如何通过命令行将IPython Notebook转换为Python文件?

我有这个问题,并试图在线找到解决方案。 虽然我找到了一些解决方案,但它们仍然存在一些问题,例如,当您从仪表板启动新笔记本时,会出现恼人的~/.jupyter/jupyter_notebook_config.py自动创建。

所以最终我写了自己的解决方案:

import io

import os

import re

from nbconvert.exporters.script import ScriptExporter

from notebook.utils import to_api_path

def script_post_save(model, os_path, contents_manager, **kwargs):

"""Save a copy of notebook to the corresponding language source script.

For example, when you save a `foo.ipynb` file, a corresponding `foo.py`

python script will also be saved in the same directory.

However, existing config files I found online (including the one written in

the official documentation), will also create an `Untitile.txt` file when

you create a new notebook, even if you have not pressed the "save" button.

This is annoying because we usually will rename the notebook with a more

meaningful name later, and now we have to rename the generated script file,

too!

Therefore we make a change here to filter out the newly created notebooks

by checking their names. For a notebook which has not been given a name,

i.e., its name is `Untitled.*`, the corresponding source script will not be

saved. Note that the behavior also applies even if you manually save an

"Untitled" notebook. The rationale is that we usually do not want to save

scripts with the useless "Untitled" names.

"""

# only process for notebooks

if model["type"] != "notebook":

return

script_exporter = ScriptExporter(parent=contents_manager)

base, __ = os.path.splitext(os_path)

# do nothing if the notebook name ends with `Untitled[0-9]*`

regex = pile(r"Untitled[0-9]*$")

if regex.search(base):

return

script, resources = script_exporter.from_filename(os_path)

script_fname = base + resources.get('output_extension', '.txt')

log = contents_manager.log

log.info("Saving script at /%s",

to_api_path(script_fname, contents_manager.root_dir))

with io.open(script_fname, "w", encoding="utf-8") as f:

f.write(script)

c.FileContentsManager.post_save_hook = script_post_save

要使用此脚本,您可以将其添加到~/.jupyter/jupyter_notebook_config.py :)

请注意,您可能需要重新启动jupyter notebook / lab才能使其正常工作。

如果觉得《python的notebook怎么用_如何通过命令行将IPython Notebook转换为Python文件?》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。