SIGMA-SE Tech Blog

SIGMA-SE Tech Blog


当サイトは、過去に運営していた別ドメイン(unisia-se.com)から sigma-se.com へ移行した技術ブログです。
旧サイトの記事をもとに、内容の精査・加筆・最新化を行い再構成しています。
正確で実用的な情報提供を目的としています。

Python - 対話モード:PYTHONSTARTUPと起動時設定の使い方

概要

Pythonの対話モードの基本操作と、PYTHONSTARTUPを使った起動時スクリプトの設定方法を整理する。

対話モードは、短いコードの確認、ライブラリの挙動確認、環境変数やパスの調査に便利な実験場所になる。PYTHONSTARTUPを使うと、毎回使うimportや補助関数を起動時に読み込める。

この記事で理解できること

  • pythonコマンドで対話モードを起動する方法。
  • sys.pathなどを対話的に確認する流れ。
  • exit()やCtrl+Dで終了する方法。
  • PYTHONSTARTUPで起動時スクリプトを読み込む方法。
  • IPythonやimport thisなどの補足的な使い方。

作業前に確認すること

項目 確認内容
Pythonコマンド 利用しているPythonのバージョンを確認する。
対話モード >>> の後にコードを入力して即時実行する。
PYTHONSTARTUP 起動時に読み込むスクリプトのパスを環境変数に設定する。
共通import 毎回使う標準ライブラリを起動時に読み込める。
-iオプション ファイル実行後に対話モードへ入れる。

作業時の注意点

作業時の注意点 確認ポイント
pythonとpython3 環境によって起動するバージョンが違うことがある。
sys未定義エラー importしていないモジュールは対話モードでも使えない。
PYTHONSTARTUPの範囲 通常のスクリプト実行ではなく、対話モード起動時に効く。
アンダーバー 直前の結果を保持するため、通常変数名として使うと混乱しやすい。

実施内容

対話モードの使用例

  • 対話モードの起動
    Pythonのバージョン問わず、pythonコマンドを実行することで対話モードが起動する。
    対話モードでは、入力待ち状態を表す「>>>」の後に直接コードを書いて実行することができる。

    $ python -V    # バージョン確認
     Python 3.6.4
    $ python    # 対話モード起動 (マイナーバージョンまでを指定しても可)
     [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
     Type "help", "copyright", "credits" or "license" for more information.
     >>>
    
  • 対話モードの実行
    例えば、sys.pathを確認したい場合、実際のコーディングと同じ要領でsysをインポート後、sys.pathを実行することで、結果(pathの一覧)が表示される。

    $ python    # 対話モード起動 (マイナーバージョンまで指定した python3.6 でも同じ動作)
     [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import sys
     >>> sys.path
     ['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', 
     '/var/www/vops/lib64/python3.6/site-packages','/var/www/vops/lib/python3.6/site-packages']
     >>>
    
  • 対話モードの終了
    「Ctrl」+「D」押下または、exit()を実行する。

    $ python
     Python 3.6.4 (default, Dec 19 2017, 14:48:12)
     [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
     Type "help", "copyright", "credits" or "license" for more information.
     >>> exit()
    

環境変数(PYTHONSTARTUP)の設定

対話モードでは、環境変数PYTHONSTARTUPに指定したスクリプトを最初に実行する。
以下は、簡単な例として上記、対話モードの実行で記述したsys.pathimport sysなしで実行できるように事前に環境変数PYTHONSTARTUPに設定する手順。

  • 環境変数未設定でsys.pathを実行

    $ python
     Python 3.6.4 (default, Dec 19 2017, 14:48:12)
     [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
     Type "help", "copyright", "credits" or "license" for more information.
     >>> sys.path
     Traceback (most recent call last):
       File "", line 1, in 
     NameError: name 'sys' is not defined
     >>>
    

    sysをインポートしていないので当然エラーが発生する。

  • PYTHONSTARTUPimport sysを追記
    ホームディレクトリに.pythonstartupを作成後、環境変数「PYTHONSTARTUP」に.pythonstartupを設定し、import sysを追記する。

    $ touch  ~/.pythonstartup    # 空ファイル新規作成
    $ vim  ~/.pythonstartup    # import sys を追記
     import sys
    $ export PYTHONSTARTUP=~/.pythonstartup    # 環境変数「PYTHONSTARTUP」にpythonstartup を設定
    
  • 再度対話モードでsys.pathを実行

    $ python
     Python 3.6.4 (default, Dec 19 2017, 14:48:12)
     [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
     Type "help", "copyright", "credits" or "license" for more information.
     >>> sys.path
     ['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', 
     '/var/www/vops/lib64/python3.6/site-packages', '/var/www/vops/lib/python3.6/site-packages']
     >>>
    

    .pythonstartupを読み込んでsysをインポート後、正常にsys.pathの結果が表示されている。

上記の要領で、Pythonの標準ライブラリなどの共通モジュールを環境変数(PYTHONSTARTUP)に設定しておくと対話モードのコーディングが簡潔になる。

その他、対話モードの補足

  • 最後に実行されたコードを再度実行する
    最後に実行したコードは、変数_(アンダーバー)に格納されているため、_(アンダーバー)を実行することで再実行できる。

    $ python
     [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import sys
     >>> sys.path
     ['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', 
     '/var/www/vops/lib64/python3.6/site-packages', '/var/www/vops/lib/python3.6/site-packages']
     >>> _
     ['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', 
     '/var/www/vops/lib64/python3.6/site-packages', '/var/www/vops/lib/python3.6/site-packages']
     >>>
    
  • 任意のファイルを実行後、対話モードを起動
    -iオプションでファイルパスを指定すると、対話モードに入る前に任意のファイルを実行できる。

    $ python -i example.py
    >>>
    
  • IPythonの導入
    対話モードをデバッガーのように利用できるIPythonというパッケージもある。
    IPythonをインストールするとTABキーでの補完、シェルコマンドの使用、pythonデバッガー(pdb)との連携ができるようになる。

    $ pip install ipython
    
  • Python開発者の心構え(The Zen of Python)
    対話モードでもimport thisで原文確認できる。
    以下は、The Zen of Pythonは、Pythonの開発者の一人「Tim Peters」によって書かれたPythonらしさを端的にまとめた文章。

    • 原文

      $ python
      Python 3.6.4 (default, Dec 19 2017, 14:48:12)
      [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
      Type "help", "copyright", "credits" or "license" for more information.
      >>> import this
      The Zen of Python, by Tim Peters
      
      Beautiful is better than ugly.
      Explicit is better than implicit.
      Simple is better than complex.
      Complex is better than complicated.
      Flat is better than nested.
      Sparse is better than dense.
      Readability counts.
      Special cases aren't special enough to break the rules.
      Although practicality beats purity.
      Errors should never pass silently.
      Unless explicitly silenced.
      In the face of ambiguity, refuse the temptation to guess.
      There should be one-- and preferably only one --obvious way to do it.
      Although that way may not be obvious at first unless you're Dutch.
      Now is better than never.
      Although never is often better than *right* now.
      If the implementation is hard to explain, it's a bad idea.
      If the implementation is easy to explain, it may be a good idea.
      Namespaces are one honking great idea -- let's do more of those!
      
    • 和訳

      The Zen of Python, by Tim Peters
      
      Beautiful is better than ugly.
      醜いより美しいほうがいい。
      Explicit is better than implicit.
      暗示するより明示するほうがいい。
      Simple is better than complex.
      複雑であるよりは平易であるほうがいい。
      Complex is better than complicated.
      それでも、込み入っているよりは複雑であるほうがまし。
      Flat is better than nested.
      ネストは浅いほうがいい。
      Sparse is better than dense.
      密集しているよりは隙間があるほうがいい。
      Readability counts.
      読みやすいことは善である。
      Special cases aren't special enough to break the rules.
      特殊であることはルールを破る理由にならない。
      Although practicality beats purity.
      しかし、実用性を求めると純粋さが失われることがある。
      Errors should never pass silently.
      エラーは隠すな、無視するな。
      Unless explicitly silenced.
      ただし、わざと隠されているのなら見逃せ。
      In the face of ambiguity, refuse the temptation to guess.
      曖昧なものに出逢ったら、その意味を適当に推測してはいけない。
      There should be one-- and preferably only one --obvious way to do it.
      何かいいやり方があるはずだ。誰が見ても明らかな、たったひとつのやり方が。
      Although that way may not be obvious at first unless you're Dutch.
      そのやり方は一目見ただけではわかりにくいかもしれない。オランダ人にだけわかりやすいなんてこともあるかもしれない。
      Now is better than never.
      ずっとやらないでいるよりは、今やれ。
      Although never is often better than *right* now.
      でも、今"すぐ"にやるよりはやらないほうがマシなことが多い。
      If the implementation is hard to explain, it's a bad idea.
      コードの内容を説明するのが難しいのなら、それは悪い実装である。
      If the implementation is easy to explain, it may be a good idea.
      コードの内容を容易に説明できるのなら、おそらくそれはよい実装である。
      Namespaces are one honking great idea -- let's do more of those!
      名前空間は優れたアイデアであるため、積極的に利用すべきである。
      

実務とのつながり

  • 動作確認
    短い式や標準ライブラリの挙動をすぐ確認できる。
  • 環境調査
    sys.pathやモジュール読み込み先の確認に使える。
  • 開発効率
    よく使う準備処理をPYTHONSTARTUPへまとめられる。

要約

  • Pythonの対話モードは、小さなコードをすぐ試すための実験環境になる。
  • PYTHONSTARTUPを使うと、起動時に共通処理を読み込める。
  • バージョンや環境変数の違いに注意すると、環境調査にも使いやすい。


Copyright SIGMA-SE All Rights Reserved.
s-hama@sigma-se.jp