【问题标题】:kernel keep dying in jupyter notebook if run any code after exit()如果在 exit() 之后运行任何代码,内核会在 jupyter notebook 中死去
【发布时间】:2021-05-19 23:49:55
【问题描述】:

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

p = input("type anything for detecting error:")
if p == "hi":
    print(hellow)
else:
    print('hi')
    exit()
print(p)

结果如下: 键入任何内容以检测错误:o 你好 o

然后内核染料和笔记本泵出消息: '内核似乎已经死了。它将自动重新启动。 我退出程序后它不应该打印 o 。 enter image description here

甚至在 exit() 之后我也不打印任何东西:

p = input("type anything for detecting error:")
if p == "hi":
    print(hellow)
else:
    print('hi')
    exit()
p == "hi"

它仍然会输出内核已死的消息。 enter image description here

所以我想我在 jupyter notebook 中发现了 exit() 函数的错误,对吧? 或者它只是存在于我的电脑中? 有人能帮我解决这个问题吗,请。

【问题讨论】:

  • 为什么需要exit()?调用它会actually stop IPython
  • 因为我试着写了try和error代码,它没有退出并开始在它下面打印代码:``` fname = input('Enter the file name: ') try: fhand = open (fname) except: print("file doesn't exist!") quit() count = 0 try: for line in fhand: if line.startswith('Subject:'): count = count + 1 except: quit() print('There were', count, 'subject lines in', fname) ``` 但是如果我输入“”它就会出来:输入文件名:文件不存在!有0个主题行,所以我简化了代码并在下面提出问题。
  • 我的回答对您有帮助吗?如果是,请考虑marking it as an answer

标签: python python-3.x jupyter-notebook


【解决方案1】:

内核死机不是因为您的计算机,而是因为exit() 命令。 Jupyter Notebook 开发人员on Github 证实:

目前使用exit()会让notebook认为内核 已经死了,它会自动启动一个新的内核。

如果您只是想停止执行,请将您的代码包装在一个函数中并改用return

def my_func():
    p = input("type anything for detecting error:")
    if p == "hi":
        print(hellow)
    else:
        print('hi')

        # Use return instead of exit()
        return
    print(p)

# Call the function
my_func()

【讨论】:

  • 但是Jupiter notebook在exit()之后也做了剩下的功能,我想知道为什么,因为如果我在coursera python代码游乐场运行它,它就不会发生。
【解决方案2】:

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

def main():
    p = input("type anything for detecting error:")
    if p == "hi":
        print(hellow)
    else:
        print('hi')
        return
    print(p)
main()

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

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 2019-07-31
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多