LoginSignup
3
1

More than 5 years have passed since last update.

Python3で実行途中にインタラクティブな操作へ移る

Posted at

はじめに

 デバッグのために実行を任意の時点で一度停止して,コンソールで対話的な操作をしたいときの方法.良い方法があったので自分用に書き残しておく.

使い方

 当たり前だが下のコードでは2と3が順に出力される.

test1.py
x=2
print("x:", x)
x=3
print("x:", x)

これを途中で一時停止して対話的な操作をしてみる.

test2.py
import code

x=2
print("x:", x)
x=3
code.InteractiveConsole(globals()).interact()  #ここに達した時点で一時停止してインタラクティブな操作に移る
print("x:", x)

これを実行すると,"x = 2"が出力された後,いつものインタラクティブモードに切り替わる.

C:\Python>python test2.py
x: 2
Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

このモードの間は,普段使うコンソールと同じように使える.対話モードを終了するにはCtrl+Zを押してEnter.プログラムそのものを終了するなら通常通りexit()関数を実行する.

>>> x
3
>>> x=4
>>> ^Z

now exiting InteractiveConsole...
x: 4

この例では,最後にxを出力するので書き換えた値の4が出力される.

3
1
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
3
1