You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Visual Studio Code中捕获Python的KeyboardInterrupt问题求助

Fixing Ctrl+C Capture Issues with Intel Fortran Runtime in VS Code Python

Ah, I’ve been there before—this frustrating issue happens because the Intel Fortran Runtime (hence that forrtl error message) is intercepting the Ctrl+C signal before Python can get to it. It’s basically cutting the line between your keyboard and Python’s exception handler, which is why your try-except block never fires. Let’s walk through the fixes step by step:

1. Tell Intel Fortran Runtime to Let Python Handle Ctrl+C

The first and most critical step is to set an environment variable that disables the Fortran runtime’s console control handler. This will let the SIGINT signal reach Python’s error handling system.

Option A: Set in VS Code’s Launch Configuration

If you’re running your code via VS Code’s debug/run menu, add the environment variable to your launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal", // or "externalTerminal"
            "env": {
                "FOR_DISABLE_CONSOLE_CTRL_HANDLER": "1"
            }
        }
    ]
}

This will apply the setting automatically whenever you run your code through VS Code.

Option B: Set in Terminal Before Running

If you prefer running from the terminal (integrated or external), set the variable first:

  • Windows Command Prompt:
    set FOR_DISABLE_CONSOLE_CTRL_HANDLER=1
    python your_script.py
    
  • Linux/macOS Terminal:
    export FOR_DISABLE_CONSOLE_CTRL_HANDLER=1
    python your_script.py
    

2. Use Python’s Signal Handling or Try-Except

Once the Fortran runtime stops hogging the signal, your Python code can properly catch Ctrl+C. Here are two reliable approaches:

Approach 1: Signal Handler Function

Register a custom handler for SIGINT to define exactly what happens when Ctrl+C is pressed:

import signal
import time

def handle_ctrl_c(signum, frame):
    print("\n✅ Caught Ctrl+C! Cleaning up before exit...")
    # Add your cleanup logic here (close files, release resources, etc.)
    exit(0)

# Register the handler
signal.signal(signal.SIGINT, handle_ctrl_c)

# Your main code
print("Running... Press Ctrl+C to stop")
while True:
    time.sleep(1)

Approach 2: Try-Except KeyboardInterrupt

If you prefer a simpler structure, wrap your main code in a try-except block targeting KeyboardInterrupt:

import time

try:
    print("Running... Press Ctrl+C to stop")
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("\n✅ Caught Ctrl+C! Exiting gracefully.")

3. Edge Case: If You’re Using Fortran Extensions

If your Python code calls into custom Fortran modules, you might need to modify the Fortran code to not catch SIGINT either. In your Fortran code, avoid using signal() or ctrlc_handler functions that intercept the signal. If you must use them, make sure they pass the signal along instead of aborting the program.


内容的提问来源于stack exchange,提问作者Sadjad Anzabi Zadeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:05:49