Run Jupyter Notebook (.ipynb) from command line as

2020-07-22 19:15发布

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!

3条回答
▲ chillily
2楼-- · 2020-07-22 19:43

A workaround is a small shell script that has three parts

  1. converting the notebook
  2. executing created script
  3. removing the script

create a file 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}

use as such:

$ ./runnb.sh nbconvert_test.ipynb

EDIT: According to this answer, this command should do just fine jupyter nbconvert --execute test_nbconvert.ipynb (just leav out the --to flag

查看更多
【Aperson】
3楼-- · 2020-07-22 19:43

With the boar package, you can run your notebook within a python code, using:

from boar.running import run_notebook

outputs = run_notebook("nbconvert_test.ipynb")

For more information, see:

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

查看更多
虎瘦雄心在
4楼-- · 2020-07-22 19:59

You can send the jupyter nbconvert to stranded output and pipe that to python.

jupyter nbconvert --to script --execute --stdout test_nbconvert.ipynb | python
查看更多
登录 后发表回答