2016-11-05 2 views
1

に機能を殺すためにSIGINTを使用した:例として、次のコードを取るのPython 3

import signal 
import time 

def stop(signal, frame): 
    print("You pressed ctrl-c") 
    # stop counter() 

def counter(): 
    for i in range(20): 
     print(i+1) 
     time.sleep(0.2) 

signal.signal(signal.SIGINT, stop) 
while True: 
    if(input("Do you want to count? ")=="yes"): 
     counter() 

は、どのように私はそれがプロンプトに戻りますので、counter()機能を殺す、または破損するstop()機能になるだろうか?

出力例:

Do you want to count? no 
Do you want to count? yes 
1 
2 
3 
4 
5 
6 
7 
You pressed ctrl-c 
Do you want to count? 

私は、Python 3.5.2を使用しています。

答えて

1

かわりに、独自のSIGINTハンドラを定義するKeyboardInterrupt例外を使用することができます。

while input("Do you want to count? ").strip().casefold() == "yes": 
    try: 
     counter() 
    except KeyboardInterrupt: 
     print("You pressed ctrl-c") 
+0

私はそれが保存するスペースの量のためにこれが本当に好きです:) –

1

stopで例外を発生させると、counterの実行が停止し、最も近い例外ハンドラ(while Trueループで設定したもの)を検索できます。

カスタム例外を作成し、次のとおりです。

class SigIntException(BaseException): pass 

stopでそれを上げる:

def stop(signal, frame): 
    print("You pressed ctrl-c") 
    raise SigIntException 

とあなたのwhileループでそれをキャッチ:

while True: 
    if(input("Do you want to count? ")=="yes"): 
     try:   
      counter() 
     except SigIntException: 
      pass 

をし、それが動作しますあなたがそれを必要とする方法。

+0

天才!助けてくれてありがとうございます; D –

+0

@EddieHartがクリアされるように、PythonのデフォルトのSIGINTハンドラはKeyboardInterrupt例外を発生させます。すなわち、メインスレッドの 'counter()'関数を中断するためにデフォルトで何もする必要はありません。 – jfs

+0

@ J.F.Sebastianはい、しかし、これは私が知っている限り、これはプログラム全体を終了させるでしょうか? –

関連する問題