0

現在、UNIX 環境で SSH および Kerberos 認証方式に移行中です。スクリプトが中断されたとき、エラーが発生したとき、またはスクリプトが正常に実行されたときはいつでも、すべての自動化された Python スクリプトで Kerberos OS コマンドを発行する必要があります。bashでは終了時にトラップできることは知っていますが、私の調査によると、Pythonにはその機能がありません。私の試みはtry/except/elseブロックであり、機能しますが、直接のプロセスキルをキャッチしてコマンドを発行しません。私は決してPythonの専門家ではないので、これに対するより良いアプローチや調べる関数を知っている人はいますか? また、これはメイン関数が呼び出される単純なスクリプトでのみ機能します。私のスクリプトの一部はオブジェクト指向でより複雑であり、私のアプローチは機能しません。これが単純なループでの私の試みです。何かアドバイス?

def main():
    while (True):
        print "Interrupt Me..."

def watchForInterrupts(x):
    #define function to issue kdestroy command
    def issueKdestroy():
        import os
        os.system("kdestroy -q")
        print "issued kdestroy"
    try:
        x()
    except: 
        print "interrupted, issuing kdestroy"
        #call issueKdestroy function if interrupted
        issueKdestroy()
    #else block to issue kdestroy if script completed successfully
    else:
        print "executed successfully, issuing cleanup kdestroy"
        issueKdestroy()

#call watchForInterrupts function with main passed as a parameter 
watchForInterrupts(main)
4

3 に答える 3

1

このモジュールを使用してみてください:

http://docs.python.org/2/library/atexit.html

これは、シャットダウン フックを設定するより便利な方法を定義します。

import atexit

@atexit.register
def goodbye():
    print "You are now leaving the Python sector."

いいですね。

于 2013-04-02T04:15:32.887 に答える