はじめに
タイトルのとおりです。
コード
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
)