【问题标题】:Convert ipython notebook to directly-executable python script将 ipython notebook 转换为可直接执行的 python 脚本
【发布时间】:2017-08-10 05:19:46
【问题描述】:

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

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

ipython nbconvert --to python notebook.ipynb

但是,我想让notebook.py 直接可执行,而不必每次都手动破解它,以便我可以不断更新notebook.ipynb 并用我的更改覆盖notebook.py。我还想在notebook.py 中包含命令行参数。例如,我的样板文件是:

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

当然是chmod +x notebook.py

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

Edit1:这无异于说:

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

Edit2:这个问题是部分答案,但没有告诉我如何包含#!/usr/bin/env ipython 行:How can I check if code is executed in the IPython notebook?

Edit3: 可能有用,但前提是 %%bash /usr/bin/env ipython 可以工作 - 会不会..? How do I provide inline input to an IPython (notebook) shell command?

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[ ]:

【问题讨论】:

  • 你直接说的时候,你指的是什么方法或入口?你的意思是来自 Jupyter 笔记本吗?
  • 在 *nix 命令行上,即./notebook.py - 我知道该怎么做,但我想 (i) 导出笔记本并 (ii) 使其可执行而无需破解它每次都用手,还允许通过例如命令行参数sys.argv
  • 我已经编辑了这个问题 - 编辑有意义吗?

标签: python bash ipython jupyter-notebook ipython-notebook


【解决方案1】:

结果证明是相当简单的。

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

here 所述,nbconvert 可以使用任意模板进行自定义。

所以创建一个文件hashbang.tpl 包含:

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

然后在命令行执行:

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

你好:

> more notebook.py

#!/usr/bin/env ipython

# coding: utf-8

# In[1]:

print 'Hello'
...

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

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

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 2013-10-26
    • 1970-01-01
    • 2015-07-24
    • 2017-09-19
    • 2014-06-19
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多