В VSCode отладчик Python запускает новый терминал каждый раз, когда я отлаживаю

При отладке в Python в VS Code каждый раз при отладке создается новый терминал. Код просто добавляет терминал каждый раз в раскрывающийся список в окне терминала. Мне приходится вручную удалять каждый терминал или через некоторое время удалять их кучу - иначе он в конечном итоге зависнет.

Есть ли параметр, позволяющий остановить это? Это ожидаемое поведение или дефект?


Обновление: вот скриншот того, что происходит, когда каждый раз создается новый терминал отладки. Это раскрывающийся список в правой части окна терминала, который вы можете открыть или перейти с помощью ctrl-`(клавиша могилы, несмещенная тильда или клавиша ~). Он показывает обычный терминал bash, терминал Python, который повторно используется при каждом запуске скрипта, но 3 окна консоли отладки Python. Новая консоль отладки Python создается каждый раз, когда вы debug (F5). Поэтому мне нужно войти и вручную удалить консоль отладки Python (нажмите значок мусорного бака справа) каждый раз, когда я отлаживаю. Это открывало до 20+ окон терминала, прежде чем я понял, что это происходит.

1 ответ

Решение

A Real Solution: Get the terminal to exit afterward!

Finally saw a real solution to this (well, a little hacky), in this answer - at least if you are using Git Bash as your default terminal.

If you add arguments && and exit to the debug configuration, the debug terminal will automatically exit after your program ends. Be warned though, it will immediately close the terminal, and all the text in it (you might need to add a "Press any key to end program" at the end of your script to give you time to review any text, or something like that).

Note: This is still a hack and it doesn't always work - if you hit the "restart" or "stop" buttons on the debugger toolbar, it will shortcut this method

The && basically tells Bash to stop and wait for the debug task to finish before continuing with additional commands, and then the exit will execute after your debug session ends, which closes the terminal.

You can do this by opening your run/debug configuration as follows:

  1. Go to the "Run" window in the sidebar
  2. Select the run configuration in the dropdown then press the gear, which will bring up the corresponding launch.json file in an editor window.

  1. Add the line for args: ["&&", "exit"] as shown below, and MAKE SURE YOU ADD A COMMA AT THE END OF THE LINE ABOVE THAT!!

launch.json:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "args": ["&&", "exit"]
        }
    ]
}

NOTE 1: A comment left at that answer indicates you might want to try "args": ["\n", "exit", "0"] if that doesn't work. This is likely for a different terminal type (Windows Cmd Prompt, PowerShell, different Linux shell, etc.).

NOTE 2: If you need to add other arguments, you can add them as strings before the "&&" argument in the list. Items placed earlier in the list will become arguments to your actual program/script.



Alternative (Original) Solution: Use the Debug Console for output (Alternative Solution)

After some searching, I cannot determine if it is expected behavior to launch a new terminal for each debug, but there is a workaround.

Setup your debug configuration for Python: Current File. On the debug tab, at the top, click the gear icon to open launch.json

Note: The debug icon below changed slightly and this tab is now called Run instead of Debug

In launch.json, change the "console" setting from the default of "integratedTerminal" to "internalConsole", as shown below:

{   "version": "0.2.0",
    "configurations": [
        {   "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "internalConsole"
        }
    ]
}

This will cause all output of any debug session to only happen in the DEBUG CONSOLE, which gets cleared and reused each session, rather than spawning a new integrated terminal every session.


The downside

I ended up going back to the integrated terminal for scripts that expect user input at the console, because the debug console does not allow user input.

In that case, you just need to constantly delete the extra debug sessions - a bit of a pain.

Другие вопросы по тегам