Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught?

后端 未结 3 824
醉话见心
醉话见心 2020-11-29 23:58

The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionabl

相关标签:
3条回答
  • 2020-11-30 00:14

    You can also use quit, see example below:

    while True:
    print('Type exit to exit.')
    response = input()
    if response == 'exit':
        quit(0)
    print('You typed ' + response + '.')
    
    0 讨论(0)
  • 2020-11-30 00:23

    As Jerub said, os._exit(1) is your answer. But, considering it bypasses all cleanup procedures, including finally: blocks, closing files, etc, and should really be avoided at all costs, may I present a "safer-ish" way of using it?

    If you problem is SystemExit being caught at outer levels (ie, unittest), then be the outer level yourself! Wrap your main code in a try/except block, catch SystemExit, and call os._exit there, and only there! This way you may call sys.exit normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and then calling os._exit.

    You can even choose which exits are the "emergency" ones. The code below is an example of such approach:

    import sys, os
    
    EMERGENCY = 255  # can be any number actually
    
    try:
        # wrap your whole code here ...
        # ... some code
        if x: sys.exit()
        # ... some more code
        if y: sys.exit(EMERGENCY)  # use only for emergency exits
        # ...
    except SystemExit as e:
        if e.code != EMERGENCY:
            raise  # normal exit, let unittest catch it
        else:
            os._exit(EMERGENCY)  # try to stop *that*, sucker!
    
    0 讨论(0)
  • 2020-11-30 00:28

    You can call os._exit() to directly exit, without throwing an exception:

    import os
    os._exit(1)
    

    This bypasses all of the python shutdown logic, such as the atexit module, and will not run through the exception handling logic that you're trying to avoid in this situation. The argument is the exit code that will be returned by the process.

    0 讨论(0)
提交回复
热议问题