python - 如何从自定义库结束主函数?

标签 python exit exit-code quit

我使用一系列不同的 python 脚本来实现各种功能。为了帮助实现这一点,我将所有可重用函数组织到自定义库中。然而,我发现其中许多函数会由于奇怪的原因而出错,有些是已知的,有些是未知的。我设计了下面的函数,至少让我在向我抛出巨大的回溯之前看到错误消息。我在一个库中有以下命令:

FooBar = trace_check(lambda: Foo(bar))

这是一个单独库中的错误捕获函数:

def trace_check(func):
    try:
        return func()
    except:
        TracebackString = traceback.format_exc() ###This gets the traceback as a string.
        type, message, tracebacklocation = sys.exc_info() ###This gets the components, particularly the message.
        print "An error has occurred with the following error message:"
        print type    ###Example is IOError
        print message     ###The message associated with the error
        TracebackPrompt = ask("Do you want to see the entire traceback?") #Returns True/False value
        if TracebackPrompt:
            print TracebackString
        print 'Exiting Python Script' ###This shows me it gets to this point.
        sys.exit(0)  ###This is the problem
        print "Did it work?"    ###This statement does not print, so exit worked...

当trace_check运行并且出现错误时,sys.exit只会将函数退出到main(),而不是结束main。如果我使用 os._exit() 代替, main() 函数会正确结束,但运行脚本的程序也会终止。一个命令不够强大,另一个命令又太过分了……我该怎么做才能确保 main() 函数结束?

注意:我尝试将我的trace_check函数的主要部分放入第一个库中,但同样的事情发生在库调用结束但不是main()时。

tl;dr - Python:main() 调用库中的函数,该函数调用单独库中的第二个函数。第二个函数有一个 sys.exit() 命令,该命令仅退出到 main() 而不是结束 main()。 os._exit() 会杀死 shell 并且过度杀伤(需要重新启动 shell TT^TT)。还有另一种方法可以从函数库中结束 main() 吗?

最佳答案

直接回答你的问题,如果你想处理 sys.exit()从 main 调用,那么您应该捕获 sys.exit() 引发的 SystemExit 异常。下面的示例代码说明了如何执行此操作。

import sys


def func():
    sys.exit(1)


def main():
    try:
        func()
    except SystemExit:
        print 'Someone sys.exit()d'
    return 0


if __name__ == '__main__':
    sys.exit(main())

但是!您可能应该重新设计您的库。当发生意外情况时,您应该引发异常,而不是调用 sys.exit() 。让库突然退出解释器是糟糕的设计。

关于python - 如何从自定义库结束主函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23276186/

相关文章:

python - 当多处理 Python 关闭时外部程序正在运行

python - Tensorflow:global_step 不递增;因此 exponentialDecay 不起作用

c# - 如何使用 SetConsoleHandler() 来阻止退出调用

iphone - Xcode 退出代码和信号

haskell - 返回默认 Prelude> 屏幕 GHC 7.8.3 的 Haskell 程序退出代码的示例实现是什么

python - 在 django python 中扩展查询集

python - 使用 pandas 更新 CSV 文件中的 Nan 值,并在 CSV 的其他列上使用 if else 条件

perl - 为什么在Perl中使用退出代码255而不是-1?

java - 失败时在 ANT 中执行默认任务

python - IndexError : list index out of range , while finding the first non-consecutive number in a list in python