LoginSignup
48
36

More than 5 years have passed since last update.

Jupyter Notebook (*.ipynb)をダブルクリックで開くためのMacアプリケーション

Last updated at Posted at 2016-04-27

概要

Jupyter Notebook (*.ipynb)をダブルクリックで開くためのアプリケーションJupyter Launcher.appを、MacのAutomatorを使って作成します。buq様のオリジナルのアイデア (ipython notebook のファイルをダブルクリックで開く @ OS X)をもとに、個人的に追加したい機能のためにいくつかの変更を行います。ついでにPythonで書き直しています。

dock_screenshot.png

追加機能と変更点

  • アプリ自体をクリックで実行したときはJupyterのツリー画面を表示する
  • Jupyter Notebookのホームを/から~/に変更する (上記における利便性と安全性のため)

細かな改善点

  • Jupyterが確実に起動するまでウェイトする (while文の部分。特にMac起動直後では定数時間のウェイトだと間に合わない場合もあるため)
  • そのため、Jupyterの起動確認はnetstatではなくlsofを使用する (netstatはブラウザが起動しない限りゼロを返し続けてしまうため)

作成手順

  1. Automator.appを起動し、新規アプリケーションを選択し作成開始
  2. アクションからシェルスクリプトを実行を選択
  3. シェルは/usr/bin/pythonを選択
  4. 入力の引き渡し方法は引数としてを選択
  5. 以下のPythonスクリプトをウィンドウに入力
  6. Jupyter Launcher.appとして/Applicationsに保存
  7. お好みでアイコンを設定して完成

automator_screenshot.png

Pythonスクリプト

2017.01.14: スクリプトをアップデート (機能面の変更はなし)

jupyter_launcher.py
# coding: utf-8

"""Script for the Jupyter Launcher Application."""

import os
import sys
import time
import webbrowser
from subprocess import Popen, PIPE


def listened(port):
    """Check if the spacified port is listened or not."""
    cmd = "lsof -i :{} | grep 'LISTEN'"
    proc = Popen(cmd.format(port), stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
    return bool(proc.communicate()[0])


def launch_jupyter(port):
    """Launch a Jupyter Notebook Server with the spacified port."""
    cmd = "bash -cl 'jupyter-notebook ~/ --port={} --no-browser &' > /dev/null 2>&1"
    proc = Popen(cmd.format(port), stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
    proc.communicate()


if __name__ == '__main__':
    PORT = 8888
    ipynbs = sys.argv[1:]

    if not listened(PORT):
        launch_jupyter(PORT)

    while not listened(PORT):
        time.sleep(0.5)

    if ipynbs:
        for ipynb in ipynbs:
            url = 'http://localhost:{}/notebooks/{}'
            path = os.path.relpath(ipynb, os.environ['HOME'])
            webbrowser.open(url.format(PORT, path))
    else:
        url = 'http://localhost:{}/tree'
        webbrowser.open(url.format(PORT))

References

48
36
3

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
48
36