본문 바로가기
목차
utils

[vscode] Debug 사용법 요약: Python + launch.json :

by ds31x 2024. 10. 9.
728x90
반응형

0. Debug 수행 중인 VSCode 화면 (Debug view) : 

VS code 에서 debug를 시작 하려면

  • activity bar에서 “벌레와 플레이 모양의 icon” 를 클릭하고
    • 나오는 패널의 상단에 위치한 Run and Debug 버튼을 누르면,
    • Debug Sidebar (= Debug view)가 열림.

  • 또는 topbar에서 Run > Start Debugging 을 선택.
  • 또는 hot key인 f5 를 누르면, Debug sidebar 가 열림.

 

  • 위 화면에서 사용된 Debug mode (or configuration)은 Current File 임.

참고로, configuration 파일을 생성(작성법은 이 문서 아래에서 다룸)하지 않은 경우,

  • Debug sidebar 상단에 재생버튼 모양의 아이콘 옆에 No configurations 이라고 보임
  • 위 화면에서 Select and Start Debug mode 라고 기재된 붉은색 박스

1. Debug 모드 설정하기 (Configuration 파일인 launch.json 생성)

1.1. active bar 의 “벌레와 플레이 모양의 icon”(Run and Debug)을 클릭 (hotkey: Ctrl+Shift+D)

  • 아래 그림과 같이 Active bar 오른쪽의 패널에 “Run and Debug” 버튼이 보임.

  • “Run and Debug” 버튼 밑에서 create a launch.json file 을 클릭.

 

1.2. 이후, 상단 중앙의 입력창 부분에서 Python 선택하고 클릭.

1.3. 이후, 지원하는 다양한 option들(특정 app type를 디버깅할지 결정함)이 drop down으로 나옴.

1.4. Python을 학습하는 경우, 주로 활성화된 Python File 디버깅하는 것을 선택함: (Debug the currently active Python file)

  • 해당 선택 이후, Python extension 은 사용자가 선택한 디버깅(현재 활성화된 python file 디버깅)을 위해
  • 미리 정의된 configuration(구성)을 내용으로 가지고 있는 launch.json 파일을 생성 하고
    이를 editing할 수 있게 열어줌.
    • 가장 일반적이고 공통적으로 사용되는 configuration만 기본으로 작성되어짐.
    • editor에 열린 Python File을 디버깅하는 launch.json을 편집하여
    • 새로운 arguments 등을 추가하여 customizing 이 가능함.
  • 특정한 app type별 디버깅 설정 은 다음 URL을 참고 : https://code.visualstudio.com/docs/python/debugging#_debugging-specific-app-types

Add Configuration을 통해 launch.json 파일에 새로운 configuration의 추가도 가능함.

  • {$workspaceFolder} 밑에 .vscode 디렉토리 밑에 launch.json 이 존재.
  • 다음 그림은 Add Configuration 을 보여주고 있음.

 


2. Basic Debugging

Python script를 디버깅하는 가장 간단한 방법:

  • 해당 파일을 선택하여 디버깅할 script 파일이 activation 된 상태에서,
  • 상단의 “벌레와 플레이 모양의 아이콘” 옆에 있는 down-arrow 를 클릭하여
  • Debug Python File을 클릭하는 것임.

앞서 다룬 Configuration file (= launch.json)이 생성되고 나면,
디버깅할 python script 파일이 열린 탭을 선택한 상태에서 F5 hotkey를 통해 디버깅을 시작할 수 있음.


3. Debugging 관련 Toolbar와 Hotkeys

  • continue: F5 ; 다음 break point 까지 실행.
  • step over: F10 ; 현재 line에서 한 statement 씩 실행
  • step into: F11 ; 현재 statement에서 호출하는 함수 등의 안으로 들어가서 실행이 수행됨.
  • step out: Shift+F11 ; 현재 함수 수행을 종료하고 바깥으로 이동.
  • restart: Ctrl+Shift+F5 ; 재시작.
  • stop: Shift+F5 : 종료.

3-1. DEBUG CONSOLE

디버그 콘솔에서도 변수들 을 다룰 수 있음: (보통은 Debug Sidebar의 Watch를 이용함)

만약 디버그 콘솔이 보이지 않는다면,

  • VS Code의 우측 하단에서 디버그 콘솔을 선택하거나
  • ... 메뉴에서 선택.

그런 다음 콘솔 하단의>프롬프트에서 다음 expression들을 입력해볼 수 있음:

Debug 중에는 하단의 Debug Console을 통해 현재 variable들의 값들 또는 expression의 값을 확인 가능함 (아래 그림 참고).

Debug Console의

하단의 > prompt에 expression등을 입력(위 그림에서 아래쪽 붉은 박스)하여

현재 상태에서 특정 처리를 한 값들도 확인 가능함.


3-2. Debug Sidebar ***

아래 그림에서 active bar 옆의 debug sidebar에는 다음의 항목들이 존재함.

VARIABLES 의 경우,

현재 수행중인 code line의 위치에 따른 Locals scope의 변수들과 Globals scope의 변수들을 확인 가능.

https://ds31x.tistory.com/45#%EC%B0%B8%EA%B3%A0-local-variable-vs.-global-variable

 

[Python] scope와 키워드 global, nonlocal

Python에서 scope는namespace와 밀접하게 관련이 있는 개념이며,이와 관련된 주요 키워드가 nonlocal과 global이 있음.https://dsaint31.tistory.com/entry/Basic-namespace-frame-and-context [Basic] namespace, frame, and contextNamespa

ds31x.tistory.com

 

WATCH 의 경우,
확인하고자 하는 변수나 expression 을 기재하면 값을 확인할 수 있음.

https://dsaint31.tistory.com/514

 

[Python] Expression vs. Statement

Expression (표현식)프로그래밍 또는 컴퓨터 과학 분야에서 Expression은 흔히, function call, identifier, number, operator, literal 등으로 이루어진다.표현식(or 수식) 으로 번역.하나의 value로 reduce 될 수 있는 code

dsaint31.tistory.com

 

CALL STACK 에서는
function 등이 어떤 순서로 호출이 되었는지의 stack tracing 정보를 확인할 수 있음.

  • Call Stack은 함수가 호출될 때마다 생성되는 실행 컨텍스트(context)를 쌓아올리는 구조.
  • 스택구조이므로 LIFO (Last-In, First-Out) 방식으로 동작하며, 가장 나중에 호출된 함수가 먼저 실행을 마치고 스택에서 제거.

https://dsaint31.tistory.com/508

 

[Basic] namespace, frame, and context

Namespace프로그래밍 등에서 나오는 namespace는 일종의 추상적인 개념변수와 함수, 클래스 들의 이름(name)이 정의되고 사용될 수 있는 범위(scope)를 지칭함. (때문에 scope 란 용어와 자주 같이 사용됨)v

dsaint31.tistory.com

 

최하단의 BREAKPOINTS에는 설정된 break points를 확인 및 조작이 가능함.


4. Breakpoints and Logpoints

4-1. Conditional Breakpoints

브레이크포인트

  • expression (해당 expression이 true인 경우)과 hit count, 또는 둘 다 사용하여
  • 특정 조건을 만족하는 경우에만 해당 브레이크포인트 에서 실행이 멈추도록 할 수 있음.

자세한 내용은 VS Code 디버깅 메인 문서의 Conditional Breakpoints을 참조하세요.


4-2. Invoking a breakpoint in code

다음의 code로 브레이크포인트를 설정할 수 있음.

# debugpy.breakpoint() # Python 3.7 이전 버전.
breakpoint() # 3.7+ 에서 추가됨. vscode에선 debugpy이고, 보통은 pdb.
  • import debugpy 를 해줄 것.
  • 해당 라인의 다음 라인을 수행하기 직전에 수행이 멈춤.
  • 해당 코드의 다음 라인에 breakpoint를 설정한 것과 같은 효과

전통(?)적인 pdb와 ipdb와 비슷하지만

debugpy는 vscode를 위한 디버깅 패키지이며 원격 디버깅을 염두에 둔 패키지임.

주로 vscode나 IDE 에서 연결하여 디버깅하기 위해 사용됨.

2024.09.25 - [Python] - [Py] Debugging: pdb and ipdb

 

[Py] Debugging: pdb and ipdb

pdb (Python DeBugger)는 Python 표준 라이브러리에 포함된 기본 디버거이고 ipdb (IPython DeBugger)는 pdb를 기반으로 IPython의 기능을 결합한 확장 디버거임. Python 개발시 사용되는 도구로,다음에 소개되는 명

ds31x.tistory.com


4-3. Logpoints

Use Logpoints instead of print statements

 

개발자들은 종종 소스 코드에 print 문을 추가하여(원문에선 litter라고 표기하여 산재시킨다고 애기함) 

  • 변수를 빠르게 검사하기 위해
  • 디버거에서 중지 후 각 코드 라인을 일일이 단계별로 실행하지 않고 한번에 확인함.

이를 위해 VS Code에서는 logpoint를 제공함.

  • 로그포인트 는 브레이크포인트와 비슷하지만 콘솔에 메시지를 기록하고
  • 프로그램을 중지하지 않는다는 점이 다름.

일반적인 문자열을 지정하면 되는데 curly bracket {}으로 둘러싸인 expression을 사용할 수 있음:

test: {sys.argv}
  • "test: " 문자열과 sys.argv 리스트의 내용이 Debug Console 로 출력됨.

 

자세한 내용은 VS Code 주요 디버깅 문서의 로그포인트 섹션을 참조하할 것.


4-4. Triggered Breakpoint

vscode 1.86 + 부터 "Add Triggered Breakpoint" 가 추가됨.

다른 브레이크포인트가 먼저 hit될 때까지 비활성화되어 있다가, 그 조건이 충족되면 활성화되는 브레이크포인트임.

22번 라인의 breakpoint 가 hit 된 이후 활성화되는 triggered breakpoint를 설정하는 화면.


5. Set configuration Options: launch.json 작성법

다음은 lauch.json 의 주요 항목에 대한 설명임.

비슷한 tasks.json 의 설정은 다음 url을 참고: 2023.08.18 - [개발환경] - [Env] Vscode: task runner 설정: tasks.json

5-1. name

"configurations" 밑에 각각의 디버깅 설정의 이름에 해당. Mandatory option


5-2. type

python 용 디버깅 설정들은 모두 "python" 값을 가져야 함. Mandatory option


5-3. request

디버깅 모드(수행방식)를 지정한다.

  • "launch" : "program" 키에 지정된 파일(=script file)을 수행시켜 디버깅 시작
  • "attach" : 기존의 수행 중인 process를 디버깅하는데 사용됨. See Remote debugging for an example

5-4. program

"launch"로 수행할 python file.

  • Provides the fully qualified path to the python program's entry module (startup file).
    • "${file}" 이라고 기재할 경우, 현재 editor에서 active인 파일이 지정됨.
    • "${workspaceFolder}" 는 현재 vscode의 워크스페이스 경로로 치환됨.
  • Example
      "program": "${workspaceFolder}/pokemongo_bot/event_handlers/__init__.py",
  • "program": "/Users/Me/Projects/PokemonGo-Bot/pokemongo_bot/event_handlers/__init__.py",

5-5. module

python -m argument에 해당하는 module name이 기재됨 (디버깅할 module명)


5-6. python

The full path that points to the Python interpreter to be used for debugging.

  • 지정되지 않을 경우의 기본값은 "${command:python.interpreterPath}" 임.
  • 디버깅 시 python interpreter를 변경하고자 할 때 사용.

5-7. pythonArgs 

디버깅에서 Python interpreter에게 넘겨질 argument임. 다음의 syntax로 기재.

"pythonArgs": ["<arg 1>", "<arg 2>",...]

5-8. args ***

디버깅하는 main script 파일(=python program)에 넘겨주는 argument들.

"args": ["--quiet", "--norepeat", "--port", "1593"],

5-9. stopOnEntry

true로 설정된 경우, 실행 코드의 첫번째 라인에서 멈춤.
기본은 false이며 breakpoint까지 수행됨.


5-10. console

따로 수행시 terminal이 열려 debugging하려면 "console" 키를 "externalTerminal" 이라고 입력.

기본은 "integratedTerminal"임.

{
    // 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",
            "justMyCode": true
        },
        {
            "name": "Python: Current File (External Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "externalTerminal",
            "justMyCode": true
        }
    ]
}

Windows에서는 큰 문제가 없지만, wsl에서 사용할 경우 external terminal인 xterm 이 있어야 함.


5-11. autoReload

true 로 설정된 경우, 브레이크포인트에 정지해있는 상황에서 코드 상의 변화가 있을 경우,
디버거가 자동으로 해당 모듈을 다시 로드하도록 해줌.

 

다음을 참고.

{
  "name": "Python: Current File",
  "type": "python",
  "request": "launch",
  "program": "${file}",
  "console": "integratedTerminal",
  "autoReload": {
    "enable": true
  }
}

5-12. cwd

current working directory를 지정.

  • 기본으로는 "${workspaceFolder}" 임.
  • active file 의 디렉토리로하려면 "${fileDirname}"

5-13. redirectOutput

true 로 설정된 경우

  • ("console""internalConsole" 인 경우엔 true 기본임),
  • 디버거는 모든 출력을 vscode이 debugger output window로 보냄.

false 로 설정된 경우

  • ("console""integratedTerminal" 또는 "externalTerminal" 인 경우엔 false가 기본임),
  • 프로그램의 출력은 debugger output window에 보내지지 않음.

 

This option is typically disabled when using "console": "integratedTerminal" or "console": "externalTerminal" because there's no need to duplicate the output in the debug console.


5-14. justMyCode

true가 기본값이며, 개발자가 작성한 code만을 디버깅함.


References

https://code.visualstudio.com/docs/python/debugging

 

Debugging configurations for Python apps in Visual Studio Code

Details on configuring the Visual Studio Code debugger for different Python applications.

code.visualstudio.com

https://code.visualstudio.com/docs/editor/debugging

 

Debugging in Visual Studio Code

One of the great things in Visual Studio Code is debugging support. Set breakpoints, step-in, inspect variables and more.

code.visualstudio.com

cli 기반 디버깅: 2024.09.25 - [Python] - [Py] Debugging: pdb and ipdb

 

[Py] Debugging: pdb and ipdb

pdb (Python DeBugger)는 Python 표준 라이브러리에 포함된 기본 디버거이고 ipdb (IPython DeBugger)는 pdb를 기반으로 IPython의 기능을 결합한 확장 디버거임.참고로 debugpy 는 vscode에서 python debugging을 위해 제

ds31x.tistory.com

2023.12.25 - [Python] - [Python] Debugging : Traceback, Stacktrace, Backtrace ...

 

[Python] Debugging : Traceback, Stacktrace, Backtrace ...

동의어Python에서는 tracback (역추적) 이라는 용어가 많이 사용되지만,stack trace 또는 back trace라고도 불린다.의미Python의 실행 등에서 에러가 발생할 경우 출력되는 traceback 은해당 에러가 발생한 지

ds31x.tistory.com

2024.09.25 - [Python] - [Py] Debug: Error and Exception.

 

[Py] Debug: Error and Exception.

1. ExceptionPython의 모든 (다룰 수 있는) 예외(Exception)의 상위 클래스.Exception: 영어로 “예외”, “특별한 경우”, 또는 “일반 규칙에서 벗어난 것”을 의미. Python 프로그램에서 예외(exception)는정상

ds31x.tistory.com


 

2025.01.17 - [utils] - [summary] vscode

 

[summary] vscode

vscode 소개 (visual studio 와 비교)https://ds31x.blogspot.com/2023/07/env-visual-studio-code-and-visual-studio.html?view=classic [Env] Visual Studio Code and Visual StudioVisual Studio Code (vscode)는 IDE임을 강조하는 Visual Studio와 달리, c

ds31x.tistory.com


 

728x90

'utils' 카테고리의 다른 글

[vscode] gcc 사용한 C/C++ 프로젝트 환경 구축.  (1) 2025.01.19
[summary] vscode  (1) 2025.01.17
[Utils] homebrew - Summary  (0) 2024.09.08
[Summary] Package Manager  (1) 2024.09.08
[Utils] winget 간단 사용법  (0) 2024.09.08