【问题标题】:Python not catching KeyboardInterrupt when stopping with code runner使用代码运行器停止时,Python 未捕获 KeyboardInterrupt
【发布时间】:2020-07-15 14:09:49
【问题描述】:

当使用 ctrl+alt+m 停止脚本时,python 不会将其视为中断。我想在退出前执行一个清理脚本。

if __name__ == "__main__":
    try:
        main()

    except KeyboardInterrupt:
        print("keyboardInterrupt")

    finally:
        handle_cleanup()

代码运行器如何停止代码以及实现目标的选择是什么?

【问题讨论】:

  • 尝试使用 ctrl+c
  • 代码运行器不支持输入,我知道@JenilDave。

标签: python visual-studio-code vscode-code-runner


【解决方案1】:

我认为你可以使用 atexit 模块:

import atexit

def main ():
  atexit.register(handle_cleanup)
  ...

if __name__ == "__main__":
  main()

【讨论】:

  • 我试过你说的,它不适用于代码运行器,但它确实适用于“香草”终端。
  • 你是对的。尚未尝试在 VSCode Code Runner 上进行测试。请问VSCode Code Runner真的有必要吗?
  • 其实不是,但我更喜欢它有多干净。不显示directroy和其他类似终端会做的东西。
  • 如果这是你想要的,你可以在终端上export PS1='> '。这样一来,提示将只是>
  • 似乎使用 VSCode Code Runner is not possible using the exit announcement from process 来执行这种操作。我附加的链接有一个 Node 解决方法,但我不知道 Python 是否有类似的解决方法。
猜你喜欢
  • 2020-07-24
  • 2020-03-15
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2022-08-03
  • 1970-01-01
相关资源
最近更新 更多