如何在 jupyter notebook 上将 python 脚本保存为 .py 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52885901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:13:03  来源:igfitidea点击:

How to save python script as .py file on jupyter notebook

pythonsavejupyter

提问by MayOJ

I wrote some functions on Jupyter notebook and want to save the script in form of .py, but anaconda jupyter notebook automatically saves the script as .ipynb, How can I change it to .py for this specific script? Is there any command for it? Thanks

我在 Jupyter notebook 上写了一些函数,想以 .py 的形式保存脚本,但是 anaconda jupyter notebook 自动将脚本保存为 .ipynb,对于这个特定的脚本,我如何将其更改为 .py?有什么命令吗?谢谢

采纳答案by Aivar Paalberg

There are built-in Magic commandsin Jupyter:

Jupyter 中有内置的 Magic 命令

IPython has a set of predefined ‘magic functions' that you can call with a command line style syntax. There are two kinds of magics, line-oriented and cell-oriented. Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Lines magics can return results and can be used in the right hand side of an assignment. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.

Magics are useful as convenient functions where Python syntax is not the most natural one, or when one want to embed invalid python syntax in their work flow.

IPython 有一组预定义的“魔法函数”,您可以使用命令行样式语法调用它们。有两种魔法,面向线和面向细胞。行魔法以 % 字符为前缀,其工作方式与 OS 命令行调用非常相似:它们将行的其余部分作为参数获取,其中参数在传递时不带括号或引号。Lines magics 可以返回结果,并且可以在赋值的右侧使用。Cell magics 以双 %% 为前缀,它们是不仅将行的其余部分作为参数,而且在单独的参数中将其下方的行作为参数的函数。

在 Python 语法不是最自然的情况下,或者当人们想在他们的工作流程中嵌入无效的 Python 语法时,魔术作为方便的函数很有用。

%%writefile(Write the contents of the cell to a file)

%%writefile(将单元格的内容写入文件)

%save(Save a set of lines or a macro to a given filename)

%save(将一组行或宏保存到给定的文件名)

回答by sconfluentus

You can download a copy of the python as a .pyscript from FILEmenu in the upper left corner. See this photograph.enter image description here

您可以.pyFILE左上角的菜单中下载 python 的副本作为脚本。看到这张照片。在此处输入图片说明

That should do it!

应该这样做!

回答by Sarath Ak

you can try this in command line

你可以在命令行中试试这个

ipython nbconvert --to python mnist.py.ipynb.

to convert all

转换所有

 ipython nbconvert --to python *.ipynb