0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ipynb→py変換時にセル最後が変数の場合 print文に変換する

Last updated at Posted at 2025-08-23

はじめに

タイトルのとおりです。

コード

import ast
import nbformat
from nbconvert import PythonExporter
from nbconvert.preprocessors import Preprocessor

class LastExprToPrintPreprocessor(Preprocessor):
    def preprocess_cell(self, cell, resources, index):
        if cell.cell_type == "code" and cell.source.strip():
            try:
                tree = ast.parse(cell.source)
                if tree.body and isinstance(tree.body[-1], ast.Expr):
                    # セル最後の行が変数なら print(...) に置換
                    last_expr = tree.body[-1].value
                    print_call = ast.Expr(
                        value=ast.Call(
                            func=ast.Name(id="print", ctx=ast.Load()),
                            args=[last_expr],
                            keywords=[]
                        )
                    )
                    tree.body[-1] = print_call
                    cell.source = ast.unparse(tree)
            except Exception:
                pass
        return cell, resources


def convert_with_last_expr_print(
    ipynb_path,
    py_path
):
    nb = nbformat.read(ipynb_path, as_version=4)
    exporter = PythonExporter()
    exporter.register_preprocessor(LastExprToPrintPreprocessor, enabled=True)
    body, _ = exporter.from_notebook_node(nb)
    with open(py_path, "w", encoding="utf-8") as f:
        f.write(body)

使い方

ipynb_path: ipynbファイルの場所
py_path: pyファイルを出力先

convert_with_last_expr_print(
    ipynb_path,
    py_path
)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?