如果满足某些条件,我想停止在Google Datalab笔记本上执行python命令的单元格的执行。
在不影响笔记本其余部分的情况下,首选的方法是什么?
if x:
quit()
将使笔记本崩溃。
一个潜在的解决方案是将代码封装在函数中,并使用return
提前退出。
def do_work():
stopExecution = True
if stopExecution:
return
print 'do not print'
do_work()
另一个解决方案是引发一个异常:
stopExecution = True
if stopExecution:
raise Exception('Done')
print 'do not print'
一个更好的解决方案是使用if语句来允许代码执行,而不是阻止它
if ShouldIContinueWorking():
doWork()
else:
print 'Done' # do nothing (preferred) or return from function