LoginSignup
6
6

More than 5 years have passed since last update.

IPython起動時にいつも使うモジュールをimportする設定

Last updated at Posted at 2019-04-12

やりたいこと

いつも使うモジュールを毎回importするのがめんどくさいので、起動時にimportしといてもらいたい。

tl;dr

~/.ipython/profile_default/hoge.py以下にimport部分を書いておく。

IPython startup directory

たぶん、~/.ipython/profile_default/ここにディレクトリがある。
そこにREADMEがあって、
1. ここにある.py.ipyファイルを実行前に読み込んでくれる。
2. ファイル名の辞書順で実行してくれる。
的なことが書いてある。

使ってみる

適当に~/.ipython/profile_default/00-startup.pyに以下を書く。

~/.ipython/profile_default/00-startup.py
from collections import Counter
import pickle


def pload(fname):
  return pickle.load(open(fname, 'rb'))


def pdump(object, fname):
  pickle.dump(object, open(fname, 'wb'))

ipython起動して、簡単にテスト

test.
$ ipython
In [1]: pdump([1,2,3], "hoge")                                                                                                                                           

In [2]: pload("hoge")                                                                                                                                                    
Out[2]: [1, 2, 3]

In [3]: Counter("HJKLHJKLLKJLJKJKJLKJHKJJLHKLJLK")                                                                                                                                   
Out[3]: Counter({'H': 4, 'J': 10, 'K': 9, 'L': 8})

その他

入れすぎたり、重い処理を書くと起動が遅くなるから注意。
jupyter notebook, jupyter labとかも同じ設定でいけると思う。
いちおうipython hoge.pyってやれば、事前にimportしてからhoge.pyを実行くれる。
普通のpythonで起動するインタラクティブシェルの場合は環境変数のPYTHONSTARTUPにファイルのパスを設定すればいい。 https://docs.python.org/ja/3/using/cmdline.html#envvar-PYTHONSTARTUP

6
6
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
6
6