How to generate a Jupyter notebook from Python.
import nbformat
nb = nbformat.v4.new_notebook()
title = "#title"
code = """
%matplotlib inline
from sympy import *
# to print with mathjax on jupyter notebook
init_printing()
"""
nb["cells"] = [
nbformat.v4.new_markdown_cell(title),
nbformat.v4.new_code_cell(code)
]
with open("output.ipynb", "w") as f:
nbformat.write(nb, f)
With this, it seems that you can do various useful things.
PyCharm is a Python integrated development environment (IDE), which has very powerful complementary features and is the strongest Python development environment. In fact, PyCharm can work with Jupyter, and Jupyter's expressive power + PyCharm's powerful complementary function is quite comfortable.
However, when dealing with mathematical formulas, PyCharm's Jupyter output is poor, so it is better to use the browser version of Jupyter. So I don't use PyCharm's Jupyter, instead I use ʻExtranal Tools`.
Create the following script somewhere that is easy to refer to.
#!/usr/bin/env python3
# coding:utf-8
import sys
import os
import nbformat
output_dir = sys.argv[1]
output_file = input("input ipynb name:")
nb = nbformat.v4.new_notebook()
title = "#title"
code = """
%matplotlib inline
from sympy import *
init_session()
"""
nb["cells"] = [
nbformat.v4.new_markdown_cell(title),
nbformat.v4.new_code_cell(code)
]
if not output_file.endswith(".ipynb"):
output_file += ".ipynb"
with open(os.path.join(output_dir, output_file), "w") as f:
nbformat.write(nb, f)
print("ok.")
Open PyCharm's File (F) menu and select Settings ...
Select "Tools"-> "External Tools" in the settings dialog and press the "+" button.
The setting dialog will appear, so add the following items.
item | input |
---|---|
Name | Please enter a suitable name |
Description | Please enter an appropriate explanation |
Program | Python path where Jupyter is installed |
Parameters | The script path from earlier$FileDir$ |
Select "External Toos"-> "Registered Tool Name" from the right-click menu of PyCharm.
When you enter the file name in the console, various pre-filled .ipynb files will be generated from the beginning.
https://pypi.python.org/pypi/nbformat https://github.com/jupyter/nbformat
Recommended Posts