Help us understand the problem. What is going on with this article?

papermillで、Notebookの実行結果を返り値として取得

papermillでnotebookを実行した時に、こんな感じでnotebookの最後のセルの出力を値として取得できます。

nb = papermill.execute_notebook('index.ipynb', ...)
nb['cells'][-1]['outputs'][0]['text']

使い方

環境

使い方の例

下記のような、fizzbuzzを実行するだけのnotebookを定義してみます。

上記notebookをpapermillで実行するコードを記述します。別途papermillのパラメータ機能を使って引数を定義することで、notebookを引数と返り値を持つひとつの関数のように利用できます。

main.py
import papermill

def notebook_result(path, param):
    nb = papermill.execute_notebook(path, '/dev/null', dict(num=param))
    return nb['cells'][-1]['outputs'][0]['text']

print(notebook_result('fizzbuzz.ipynb', 15)) #=> fizzbuzz
$ poetry run python main.py
(中略)
fizzbuzz

参考

suzuki_sh
Windowsでコンピュータの世界が広がります
https://www.s2terminal.com
finergy-a-tm
大阪府大阪市北区角田町8番1号 梅田阪急ビル オフィスタワー35F
https://finergy.a-tm.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした