LoginSignup
16
20

More than 5 years have passed since last update.

Pythonのインタプリタをスクリプト内で実行させる

Last updated at Posted at 2017-05-09

Pythonのインタプリタをスクリプト内で実行させるには

みなさんはPythonのスクリプト内で インタプリタを実行させたい と思ったことはありませんか?
自分が作成した関数やクラスなどが最初から使えて、しかも普通のPythonコードも実行できる。
素敵ではありませんか!

基礎編

Pythonでは、code.py という、標準ライブラリ にインタプリタを実行できるものがあります。

myconsole.py
import code
console = code.InteractiveConsole(locals=locals()) # <- locals=locals() が重要
console.interact()

このように書きます。ここで code.InteractiveConsolelocals=locals() という引数を与えていますが、
locals() は自身(ここではスクリプト内)のローカル領域の変数の値を全て辞書形式で返してくれる 関数で、
これを引数に与えることによって、起動されたpythonインタプリタに スクリプト内の関数などが渡されます

このスクリプトを実行すると、

$ python myconsole.py
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

このように、Pythonのインタプリタが実行されます!

応用編

自分がこの code.py をこのように使用しました。

color.py
import code


def split_code(colorcode, sep=2):

    for index, letter in enumerate(colorcode, start=1):
        if index == 1:
            continue

        elif index % sep == 0:
            yield colorcode[index-sep:index]


def get_rgb(colorcode):

    result = []

    for element in split_code(colorcode):
        result.append( int(element, 16) )

    return result

def get_colorcode(r, g, b):

    code = hex(r) + hex(g) + hex(b)

    result = list(split_code(code))

    return "".join(result[1::2])


if __name__ == "__main__":

    code.InteractiveConsole(locals=locals()).interact()

このpythonスクリプトは、カラーコードを変換する関数が書かれています。このスクリプトを実行すると…

$ python color.py
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'split_code', 'code', 'get_colorcode', 'get_rgb']
>>>

このようにPythonインタプリタが起動し、しかも、 何もimportしなくても 作成した関数が使えるようになっております。
この何もimportしなくて良い理由は、上記のコードで locals=locals() としているからです。

もしここで、 locals=locals() としなかった場合、

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dir()
['__builtins__', '__doc__', '__name__']
>>>

このようにスクリプト内にある関数を使うことができなくなります。

参考リンク

16
20
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
16
20