PyCharm点击输入对话框Cancel按钮触发ipykernel报错的解决咨询
解决PyCharm Jupyter中点击输入对话框Cancel按钮触发KeyboardInterrupt的问题
环境说明
- PyCharm 2025.1(已免费开放Jupyter Notebook功能)
- Python 3.11 + ipykernel 6.29.5
问题场景
编写了一段循环提示用户输入指定格式问题的代码,输入空值或q时能正常退出并输出Have a good day!,但点击输入对话框的Cancel按钮时,会触发KeyboardInterrupt错误,无法正常退出。
原代码:
while True: question = input("\nStart your question about the document beginning with 'what', 'when', 'where', or 'which' (enter 'q' to quit): ") response = question.lower() if response.strip() in ('', 'q') or not (response.startswith(("what", "when", "where", "which"))): print("Have a good day!") break else: print(f"Question:\n{question}") answer = qa_chain.invoke(question) print(f"Answer:\n{answer}")
问题原因
在PyCharm的Jupyter环境中,点击输入对话框的Cancel按钮时,input()函数会直接抛出KeyboardInterrupt异常,而非返回空值,原代码的if判断无法覆盖这种异常场景。
解决方案
添加try-except块捕获KeyboardInterrupt异常,在异常处理分支中输出提示语并退出循环。
修改后的代码:
while True: try: question = input("\nStart your question about the document beginning with 'what', 'when', 'where', or 'which' (enter 'q' to quit): ") response = question.lower() if response.strip() in ('', 'q') or not (response.startswith(("what", "when", "where", "which"))): print("Have a good day!") break else: print(f"Question:\n{question}") answer = qa_chain.invoke(question) print(f"Answer:\n{answer}") except KeyboardInterrupt: print("\nHave a good day!") break
修改说明
- 将输入、判断的完整逻辑包裹在
try块中,覆盖所有可能触发异常的输入操作 - 新增
except KeyboardInterrupt分支,专门处理点击Cancel按钮触发的异常,确保退出时输出指定提示语 - 异常处理中添加换行符
\n,保证提示语的输出格式更整齐
内容的提问来源于stack exchange,提问作者punsoca
相关产品推荐
相关产品推荐

