3

I am authoring a Jupyter notebook on my local machine that will eventually be run on a remote server (which is running Ubuntu). Every time I need to make a change I must export the notebook as a .py file and then call it from the command line of the server.

I'd like to be able to run this on the fly, calling one command that takes the current .ipynb file and executes it on the command line as if it were a .py, showing all the print statements and output you'd expect if the .py were run. I thought nbconverter might do the trick using something like the following command:

jupyter nbconvert --to script --execute nbconvert_test.ipynb

As it turnout, this does not convert the .ipynb to a .py file to be executed on the command line as I would like, but rather it creates a new file called nbconvert_test.py in the same directory which I would then have to run in a separate command. I'd really like to prevent the creation of that file every time I make even a small change, and to skip the extra step on the command line.

Any help is appreciated!

4

3 回答 3

6

您可以将 jupyter nbconvert 发送到搁浅的输出并将其通过管道传输到 python。

jupyter nbconvert --to script --execute --stdout test_nbconvert.ipynb | python
于 2017-04-25T06:36:40.790 回答
1

一种解决方法是一个包含三个部分的小型 shell 脚本

  1. 转换笔记本
  2. 执行创建的脚本
  3. 删除脚本

创建文件runnb.sh

#!/bin/sh
# First argument is the notebook you would like to run
notebook=$1
scriptname="$(basename $notebook .ipynb)".py

jupyter nbconvert --to script --execute ${notebook} && python ${scriptname}
rm ${scriptname}

像这样使用:

$ ./runnb.sh nbconvert_test.ipynb

编辑: 根据这个答案,这个命令应该做得很好jupyter nbconvert --execute test_nbconvert.ipynb(只需省略--to标志

于 2017-04-25T06:23:40.647 回答
0

使用该boar软件包,您可以在 python 代码中运行您的笔记本,使用:

from boar.running import run_notebook

outputs = run_notebook("nbconvert_test.ipynb")

有关更多信息,请参阅:

https://github.com/alexandreCameron/boar/blob/master/USAGE.md

于 2020-05-24T15:44:32.707 回答