LoginSignup
78
65

More than 5 years have passed since last update.

Python で Ctrl-C をキャッチする

Posted at

Python で Ctrl-C (SIGINT) をキャッチする方法について検索すると、signal モジュールを使用する方法がよくヒットするが、もっと簡単にできるよという TIPS です。

結論から言えば、KeyboardInterrupt 例外を捕まえれば OK です。

KeyboardInterrupt を使用した場合のコード:

try:
    while True:  # なんらかの重い処理 (for だったり while だったり。。。)
        pass  # ここに、Ctrl-C で止めたい処理を書く
except KeyboardInterrupt:
    # Ctrl-C を捕まえた!
    # print('interrupted!')
    pass  # なにか特別な後片付けが必要ならここに書く
    # プログラムをこの時点で殺すなら sys.exit する
# あとは普通の処理を書けば良いが、Ctrl-C を握りつぶして処理続行は大変お行儀が悪いので注意

注意

厳密に言えば、KeyboardInterrupt はシェルから切り離されたバックグラウンドジョブの場合は SIGINT を捕まえてくれないらしいですが、通常のシチュエーションであればまず KeyboardInterrupt を使用して問題ないと思います。
(参考:https://stackoverflow.com/questions/40775054/capturing-sigint-using-keyboardinterrupt-exception-works-in-terminal-not-in-scr/40785230#40785230)

78
65
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
78
65