bash 将 ipython notebook 转换为可直接执行的 python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45605033/
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-09-18 16:21:46  来源:igfitidea点击:

Convert ipython notebook to directly-executable python script

pythonbashipythonjupyter-notebookipython-notebook

提问by jtlz2

I have a jupyter/ipythonnotebook that I am using for prototyping and tutoring.

我有一个jupyter/ipython笔记本,用于原型设计和辅导。

I export it as a python script using the menu dropdown or nbconvert, i.e.

我使用菜单下拉菜单或将其导出为 python 脚本nbconvert,即

ipython nbconvert --to python notebook.ipynb

However, I would like to make notebook.pyexecutable directly without having to hack it by hand each time, in order that I can keep updating notebook.ipynband overwriting notebook.pywith my changes. I also want to include command-line arguments in notebook.py. My boilerplate is, for example:

但是,我想notebook.py直接制作可执行文件,而不必每次都手动修改它,以便我可以不断更新notebook.ipynb和覆盖notebook.py我的更改。我还想在notebook.py. 例如,我的样板是:

#!/usr/bin/env ipython
import sys
x=sys.argv[-1]

with chmod +x notebook.pyof course.

chmod +x notebook.py当然的。

One route could be to make these lines (be they python or command-line directives) ignorable in the jupyter/ipythonnotebook - is there a way to do this by e.g. detecting the jupyter/ipythonenvironment?

一种方法可能是使jupyter/ipython笔记本中的这些行(无论是 python 还是命令行指令)可忽略- 有没有办法通过例如检测jupyter/ipython环境来做到这一点?

Edit1:This is tantamount to saying:

Edit1:这相当于说:

How can I include lines in the notebook.ipynbthat will be ignored in the notebook environment but parsed in notebook.pygenerated from it?

如何notebook.ipynb在笔记本环境中包含将被忽略但从notebook.py它生成的行中解析的行?

Edit2:This question is a partial answer, but doesn't tell me how to include the #!/usr/bin/env ipythonline: How can I check if code is executed in the IPython notebook?

Edit2:这个问题是部分答案,但没有告诉我如何包含以下#!/usr/bin/env ipython行:如何检查代码是否在 IPython 笔记本中执行?

Edit3:Could be useful, but only if %%bash /usr/bin/env ipythonwould work - would it..? How do I provide inline input to an IPython (notebook) shell command?

编辑 3:可能有用,但前提是有效%%bash /usr/bin/env ipython- 会吗..?如何为 IPython(笔记本)shell 命令提供内联输入?

Edit4:Another attempted answer (subtle): Since #is a comment in python, putting #!/usr/bin/env ipythonin the first cell of the notebook means that it will be ignored in jupyter/ipython, but respected in the exported notebook.py. However, the #!directive is not at the top, but can easily be chopped off:

Edit4:另一个尝试的答案(微妙):由于#是 python 中的注释,因此放入#!/usr/bin/env ipython笔记本的第一个单元格意味着它将在 中被忽略jupyter/ipython,但在导出的notebook.py. 但是,该#!指令不在顶部,但很容易被砍掉:

> more notebook.py 

# coding: utf-8

# In[1]:

#!/usr/bin/env ipython


# In[2]:

print 'Hello'


# In[ ]:

采纳答案by jtlz2

The answer turned out to be rather straightforward.

结果证明答案相当简单。

Part 1 - Making the exported notebook.py directly executable:

第 1 部分 - 使导出的 notebook.py 直接可执行:

As described here, nbconvertcan be customized with arbitrary templates.

如上所述这里nbconvert可以任意模板进行定制。

So create a file hashbang.tplcontaining:

所以创建一个hashbang.tpl包含以下内容的文件:

#!/usr/bin/env ipython
{% extends 'python.tpl'%}

Then at the command line execute:

然后在命令行执行:

jupyter nbconvert --to python 'notebook.ipynb' --stdout --template=hashbang.tpl > notebook.py

Hey presto:

嗨,快点:

> more notebook.py

#!/usr/bin/env ipython

# coding: utf-8

# In[1]:

print 'Hello'
...

Part 2 - Detecting the notebook environment:

第 2 部分 - 检测笔记本环境:

This answer from https://stackoverflow.com/a/39662359/1021819should do it, i.e. use the following function to test for the notebook environment:

这个来自https://stackoverflow.com/a/39662359/1021819 的答案应该可以做到,即使用以下函数来测试笔记本环境:

def isnotebook():
    # From https://stackoverflow.com/a/39662359/1021819
    try:
        shell = get_ipython().__class__.__name__
        if shell == 'ZMQInteractiveShell':
            return True   # Jupyter notebook or qtconsole
        elif shell == 'TerminalInteractiveShell':
            return False  # Terminal running IPython
        else:
            return False  # Other type (?)
    except NameError:
        return False      # Probably standard Python interpreter