Pythonで実行中のスクリプトで疑似インタプリタ
Pythonでファイルにプログラムを記述しているときに、ここでインタプリタを起動したいなあとか思う事があるわけです。そんなときに以下のコードの突っ込んで実行しているんですがもっといい方法はないかなあとか思ってる最近です。
VBみたいにGUIでブレークポイントかけて実行みたいなこと、PyDevだとできたりするのかなあ?
while True: try: inp = raw_input('>>> ') print eval(inp) except KeyboardInterrupt, e: break except Exception, e: try: exec inp except Exception, e: print
例
lst = range(10) while True: try: inp = raw_input('>>> ') print eval(inp) except KeyboardInterrupt, e: break except Exception, e: try: exec inp except Exception, e: print e
$ python t.py >>> n = range(100) >>> n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] >>> print lst [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> dir(lst) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> ^C