python trap on exit/catch系统异常并发出kerberos命令

2024-10-01 15:39:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我们目前正在迁移到unix环境中的SSH和Kerberos身份验证方案。我需要在我们所有的自动python脚本中发出Kerberos命令,只要脚本被中断、出现错误或脚本成功执行。我知道在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)

Tags: 方法函数命令脚本maindeffunctionkerberos
3条回答

我建议使用finally

def watchForInterrupts(x):
    ...
    try:
        x()
    finally: 
        # Clean up no matter what happens in try part of block
        issueKdestroy()

如果需要,可以对各种异常采取特定的操作

^{pr2}$

您还应该避免except,而不指定异常。例如,如果您在被调用函数中有一个SyntaxError,则异常处理程序会捕捉到该错误,并且您不会收到此警报。在

在另一个答案的基础上,使用try…finally并添加一个信号处理程序,以确保在发出SIGQUIT时调用finally。在

import signal
import os
import sys

def callKdestroy():
    print "call kdestroy"

def signal_handler(signum, frame):
    # ensures unwinding of Python execution.
    print "got signal"
    sys.exit(1)

signal.signal(signal.SIGTERM, signal_handler)

try:
    ...
finally:
    callKdestroy()

尝试使用此模块:

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

它定义了一种更方便的设置关闭挂钩的方法。在

import atexit

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

很好,嗯?在

相关问题 更多 >

    热门问题