#!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()
像这样的一些问题真的应该伴随着代码背后的真正意图。原因是有些问题的解决应该完全不同。在脚本的主体中,
return
可用于退出脚本。从另一个角度来看,您只需记住变量中的情况,并在try/except
构造之后实现想要的行为。或者您的except
可能测试更显式的异常类型。在下面的代码显示了变量的一个变体。变量被分配了一个函数(这里不调用赋值函数)。仅在
try/except
之后调用函数(通过变量):os._exit()
将执行低级进程退出,而不进行SystemExit
或普通python退出处理。在相关问题 更多 >
编程相关推荐