2013-03-08 1 views
5

コードが実行時例外を発生させ、補完が機能しない場合、トレースバックが出力されないため、なぜその理由が分かりません。この短いコードを試してみてください:プログラムはc = 2 + "ddda"という行でクラッシュするはずですが、明らかに文字列とintを追加しています。しかし、クラッシュする代わりに、例外は捕まえられ、何が起きているのか分かりません。プログラムは何も起こらないかのように動作し続けます。cmdのpythonモジュールを使用しているときに、プログラムを適切にクラッシュさせるにはどうすればよいですか?

import cmd 

class App(cmd.Cmd): 
    def complete_foo(self,*arg): 
     # Uncommenting this line will silently crash the progrm 
     # making it hard to debug. 
     # Is there a way to force the program to crash ? 
     c = 2 + "ddda" 
     return "d dzpo idz dza dpaoi".split(" ") 

    def do_foo(self,*args): 
     print "foo" 
App().cmdloop() 

私の質問は次のとおりです。 (cmdモジュールを使用している場合)。

+0

エラーを処理する 'try'ブロック内でコードが呼び出されない場合は、エラーとトレースバックで停止する必要があります。 – Barmar

答えて

5

残念ながら、補間の例外は、暗い深度readlineのどこかにキャッチされます。 readlineの缶の混乱の中から、あなたの端末をトレースバックを印刷するので、あなたのコンプリータをデバッグした後、デコレータを削除

import cmd 
import traceback 

def log_exceptions(fun): 
    def wrapped(*a, **kw): 
     try: 
      return fun(*a, **kw) 
     except Exception: 
      print traceback.format_exc() 
      raise 

    return wrapped 

class App(cmd.Cmd): 
    @log_exceptions 
    def complete_foo(self,*arg): 
     # Uncommenting this line will silently crash the progrm 
     # making it hard to debug. 
     # Is there a way to force the program to crash ? 
     c = 2 + "ddda" 
     return "d dzpo idz dza dpaoi".split(" ") 

 

$ python c.py 
(Cmd) foo Traceback (most recent call last): 
    File "c.py", line 7, in wrapped 
    return fun(*a, **kw) 
    File "c.py", line 20, in complete_foo 
    c = 2 + "ddda" 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

:あなたはそのような何かを試すことができます。

 

いいえ、あなたは簡単にreadlineのがクラッシュすることはできません。

+0

ありがとう。私はあなたの解決策が好きです。私は、cmdモジュールでtry/catchブロックを検索し、疑わしいものは見つけられませんでした。 readlineについてのあなたの説明は合理的な手がかりと思われ、デコレータは実用的な解決策です。再度、感謝します。 – ychaouche

+0

また、traceback.print_exc()は、トレースバックを出力することだけを望むなら、もう一つの短縮形です。 – ychaouche

+0

これは 'stderr'に出力します。これはreadlineも明らかに抑制します。 –

関連する問題