繁体   English   中英

如何直接从终端创建和打开 jupyter notebook ipynb 文件

[英]How to create and open a jupyter notebook ipynb file directly from terminal

命令jupyter notebook将打开 Jupyter 目录树页面,您可以在其中创建 ipynb 文件。

有没有办法跳过该页面并直接在浏览器上创建和打开 ipynb 文件?

我在想像 jupyter notebook mynotebook.ipynb 这样的东西

在浏览器中打开笔记本

jupyter notebook <notebook>.ipynb

创建空的、最小的笔记本:

"""create-notebook.py
   Creates a minimal jupyter notebook (.ipynb)
   Usage: create-notebook <notebook>
"""
import sys
from notebook import transutils as _
from notebook.services.contents.filemanager import FileContentsManager as FCM

try:
    notebook_fname = sys.argv[1].strip('.ipynb')
except IndexError:
    print("Usage: create-notebook <notebook>")
    exit()

notebook_fname += '.ipynb'  # ensure .ipynb suffix is added
FCM().new(path=notebook_fname)

别名 create-notebook 脚本:

alias create-notebook='python $(pwd)/create-notebook.py'

把这一切放在一起

create-notebook my_notebook && jupyter notebook my_notebook.ipynb

这不是最理想的方法。 也许有一个 Jupyter 或extensions原生的选项,但我没有遇到过,也没有遇到过这样做的需要。 该文档表明开发人员正在鼓励用户登陆仪表板。

从一个空的 Notebook Untitled.ipynb 要生成它,请保存从 jupyter 仪表板创建新笔记本时创建的默认文件。 这个空笔记本将用作在命令行中创建新的空笔记本的模板。 Untitled.ipynb的内容对我来说,jupyter 版本 4.4.0,是这样的:

$ cat Untitled.ipynb
{
 "cells": [],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}

该文件包含使用jupyter notebook Untitled.ipynb (以及最终mynotebook.ipynb )启动笔记本所需的最低限度,如果更少,它将引发NotJSONError 如果要包含默认内核,可以向模板添加一些元数据。

从这里,使用命令替换从命令行打开一个新的空笔记本,其中Untitled.ipynb是上面创建的模板笔记本的路径,而mynotebook.ipynb是您要创建的笔记本的名称:

$ jupyter notebook $(cat Untitled.ipynb >mynotebook.ipynb && echo mynotebook.ipynb)

您可以尝试以下命令。

jupyter nbconvert --to notebook --execute mynotebook.ipynb

根据Jupyter nbconvert手册下面, nbconvert--execute命令支持运行的笔记本。

在此处输入图片说明 希望它对你有用。

我有同样的痛点,并创建了nbplot来修复它: https : //github.com/nburrus/nbplot 它旨在从命令行快速在笔记本中绘制文件,但总的来说,它只是一个从模板生成笔记本并在浏览器中打开它们的小工具。 以下是如何将它与包含的空模板一起使用来回答您的问题:

pip3 install --upgrade nbplot
nbplot -t empty -o mynotebook.ipynb

它将尝试巧妙地重用现有的笔记本服务器,而不是总是启动一个新的服务器,如果您不想从一个空的笔记本开始,可以很容易地将自定义笔记本模板添加到~/.nbplot/

Jupyter 将开始在本地主机上的 Tornado 服务器上运行。 该链接类似于http://localhost/Tree当您打开笔记本时,这是在另一个页面中完成的。 你可以尝试写一个批处理脚本来调用kupyter notebok,然后用你的notebook的地址调用你的浏览器。 我认为如果笔记本不存在,未创建,则它将无法工作(页面已创建,无法打开)。

您可以使用jupytext从命令行创建一个新笔记本:

# create python file
touch foo.py

# add kernel information
jupytext --set-kernel - foo.py

# convert to notebook
jupytext --to notebook foo.py

# open in browser
jupyter notebook foo.ipynb

https://jupytext.readthedocs.io/en/latest/using-cli.html


这些命令可以包装在一个名为jupyinit的 shell 脚本中:

#!/bin/bash
# Create a new Jupyter notebook from the command line
# 
# Examples
# jupyinit env_name py_file.py py_file.ipynb

touch $2
jupytext --set-kernel $1 $2
jupytext --to notebook --execute $2
jupytext --set-formats ipynb,py $3

然后可以使用以下命令创建 OP 的示例:

$ jupyinit myenv mynotebook.py mynotebook.ipynb

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM