python-3.x 如果在exit()之后运行任何代码,内核会在jupyter notebook中不断死亡

xzlaal3s  于 2023-04-22  发布在  Python
关注(0)|答案(2)|浏览(286)

在Jupyter Notebook中运行此python代码并键入o:

  1. p = input("type anything for detecting error:")
  2. if p == "hi":
  3. print(hellow)
  4. else:
  5. print('hi')
  6. exit()
  7. print(p)

结果如下:键入任何内容以检测错误:o hi o
然后内核染色,笔记本泵出消息:'The kernel appears to have dead. It will restart automatically.'在我退出程序后,它不应该打印o。enter image description here
在exit()之后我也不会打印任何东西:

  1. p = input("type anything for detecting error:")
  2. if p == "hi":
  3. print(hellow)
  4. else:
  5. print('hi')
  6. exit()
  7. p == "hi"

它仍然会泵出内核是死消息. enter image description here
所以我想我在jupyter notebook中发现了exit()函数bug,对吗?或者它只是存在于我的电脑中?有人能帮我解决这个问题吗?

62o28rlo

62o28rlo1#

内核死亡不是因为你的计算机,而是由于exit()命令。正如Github上的Jupyter Notebook开发人员所证实的那样:
目前,使用exit()会让notebook认为内核已经死亡,它会自动启动一个新的内核。
如果您只是想停止执行,请将代码 Package 在函数中并使用return

  1. def my_func():
  2. p = input("type anything for detecting error:")
  3. if p == "hi":
  4. print(hellow)
  5. else:
  6. print('hi')
  7. # Use return instead of exit()
  8. return
  9. print(p)
  10. # Call the function
  11. my_func()
qlckcl4x

qlckcl4x2#

实际上,你可以在函数的帮助下退出Python程序,而不必关闭内核。你的代码可以这样写,

  1. def main():
  2. p = input("type anything for detecting error:")
  3. if p == "hi":
  4. print(hellow)
  5. else:
  6. print('hi')
  7. return
  8. print(p)
  9. main()

如果在IPython中调用exit()而sys.exit()引发错误,内核就会死亡,这是实现所需行为的唯一方法。

相关问题