在 python 中是否有 sys.exit() 的替代方案?
Is there an alternative for sys.exit() in python?
try:
x="blaabla"
y="nnlfa"
if x!=y:
sys.exit()
else:
print("Error!")
except Exception:
print(Exception)
我不是在问它为什么会抛出错误。我知道它会引发 exceptions.SystemExit
。我想知道是否有其他退出方式?
os._exit()
将在没有 SystemExit
或正常 python 退出处理的情况下执行低级进程退出。
诸如此类的一些问题确实应该伴随着代码背后的真正意图。原因是有些问题应该完全不同地解决。在脚本正文中,return
可用于退出脚本。从另一个角度来看,您可以只记住变量中的情况并在 try/except
构造之后实现想要的行为。或者您的 except
可能会测试更明确的异常类型。
下面的代码显示了变量的一种变体。变量被赋值一个函数(赋值的函数这里不调用)。该函数仅在 try/except
:
之后被调用(通过变量)
#!python3
import sys
def do_nothing():
print('Doing nothing.')
def my_exit():
print('sys.exit() to be called')
sys.exit()
fn = do_nothing # Notice that it is not called. The function is just
# given another name.
try:
x = "blaabla"
y = "nnlfa"
if x != y:
fn = my_exit # Here a different function is given the name fn.
# You can directly assign fn = sys.exit; the my_exit
# just adds the print to visualize.
else:
print("Error!")
except Exception:
print(Exception)
# Now the function is to be called. Or it is equivalent to calling do_nothing(),
# or it is equivalent to calling my_exit().
fn()
try:
x="blaabla"
y="nnlfa"
if x!=y:
sys.exit()
else:
print("Error!")
except Exception:
print(Exception)
我不是在问它为什么会抛出错误。我知道它会引发 exceptions.SystemExit
。我想知道是否有其他退出方式?
os._exit()
将在没有 SystemExit
或正常 python 退出处理的情况下执行低级进程退出。
诸如此类的一些问题确实应该伴随着代码背后的真正意图。原因是有些问题应该完全不同地解决。在脚本正文中,return
可用于退出脚本。从另一个角度来看,您可以只记住变量中的情况并在 try/except
构造之后实现想要的行为。或者您的 except
可能会测试更明确的异常类型。
下面的代码显示了变量的一种变体。变量被赋值一个函数(赋值的函数这里不调用)。该函数仅在 try/except
:
#!python3
import sys
def do_nothing():
print('Doing nothing.')
def my_exit():
print('sys.exit() to be called')
sys.exit()
fn = do_nothing # Notice that it is not called. The function is just
# given another name.
try:
x = "blaabla"
y = "nnlfa"
if x != y:
fn = my_exit # Here a different function is given the name fn.
# You can directly assign fn = sys.exit; the my_exit
# just adds the print to visualize.
else:
print("Error!")
except Exception:
print(Exception)
# Now the function is to be called. Or it is equivalent to calling do_nothing(),
# or it is equivalent to calling my_exit().
fn()