본문 바로가기
카테고리 없음

Run code in the debugger

by EasyGPT 2023. 12. 17.
반응형

Run code in the debugger

 

Applies to:  Visual Studio

Visual Studio는 프로젝트관리 기능, 풍부한 편집환경, 대화형창 및 Python 코드에 대한 모든 기능을 갖춘 디버깅을 제공.

디버거에서는 루프의 모든 반복을 포함하여 코드를 단계별로 실행할 수 있습니다.

특정조건이 충족될 때마다 프로그램을 일시중지할 수도 있습니다.

디버거에서 프로그램이 일시 중지되면 언제든지 전체 프로그램 상태를 검사하고 변수 값을 변경할 수 있습니다.

이러한 조치는 프로그램 버그를 추적하는 데 필수이며 정확한 프로그램 흐름을 따르는 데 유용한 도움을 제공합니다.

Visual Studio provides capabilities to manage projects, a rich editing experience, the Interactive window, and full-featured debugging for Python code. In the debugger, you can run your code step by step, including every iteration of a loop. You can also pause the program whenever certain conditions are true. At any point when the program is paused in the debugger, you can examine the entire program state and change the value of variables. Such actions are essential for tracking down program bugs, and also provide helpful aids for following the exact program flow.

1. PythonApplication1.py 파일의 코드를 다음 코드로 바꿉니다.

이 코드 변형은 make_dot_string을 확장하므로 디버거에서 개별 단계를 검사할 수 있습니다.

또한 for 루프를 main 함수에 배치하고 해당 함수를 호출하여 명시적으로 실행합니다.

Replace the code in the PythonApplication1.py file with the following code. This variation of the code expands make_dot_string so that you can examine its discrete steps in the debugger. It also places the for loop into a main function and runs it explicitly by calling that function:

Python

from math import cos, radians

# Create a string with spaces proportional to a cosine of x in degrees

def make_dot_string(x):

rad = radians(x) # cos works with radians

numspaces = int(20 * cos(rad) + 20) # scale to 0-40 spaces

st = ' ' * numspaces + 'o' # place 'o' after the spaces

return st

def main():

for i in range(0, 1800, 12):

s = make_dot_string(i)

print(s)

main()

2. F5 키를 누르거나 Debug > Start Debugging 메뉴 명령을 선택하여 코드가 제대로 작동하는지 확인하세요.

이 명령은 디버거에서 코드를 실행합니다. 아직까지 프로그램이 실행되는 동안 프로그램을 일시 중지하는 작업은 수행되지 않았으며 몇 번의 반복에 대한 물결 패턴만 인쇄할 뿐입니다.

출력 창을 닫으려면 아무 키나 누르십시오.

Check that the code works properly by pressing F5 or selecting the Debug > Start Debugging menu command. This command runs the code in the debugger. As of yet, nothing has been done to pause the program while it's running, it will just print a wave pattern for a few iterations. Press any key to close the output window.

Tip

프로그램이 완료될 때 출력 창을 자동으로 닫으려면 Tools > Options menu command을 선택하고, Python 노드를 확장하고, Debugging을 선택한 다음 프로세스가 정상적으로 종료될 때 입력 대기 옵션을 선택 취소합니다.

To close the output window automatically when the program completes, select the Tools > Options menu command, expand the Python node, select Debugging, and then clear the option Wait for input when process exits normally:

 

For more information about debugging and how to set script and interpreter arguments, see Debug your Python code.

3. 해당 줄 옆의 회색 여백을 한 번 클릭하거나 해당 줄에 캐럿을 배치하고 Debug > Toggle Breakpoint command (F9)을 사용하여 for 문에 중단점을 설정합니다.

회색 여백에 빨간색 점이 나타나 중단점을 나타냅니다(아래 화살표 참조).

Set a breakpoint on the for statement by clicking once in the gray margin by that line, or by placing the caret in that line and using the Debug > Toggle Breakpoint command (F9). A red dot appears in the gray margin to indicate the breakpoint (as noted by the arrow below):

https://smartstore.naver.com/dopza/products/4569179898

4. 디버거를 다시 시작(F5)하고 해당 중단점이 있는 줄에서 코드 실행이 중지되는지 확인합니다.

여기에서 호출 스택을 검사하고 변수를 검사할 수 있습니다.

범위 내에 있는 변수는 정의되면 Autos 창에 나타납니다. 해당 창 아래쪽에 있는 Locals view 로 전환하여 Visual Studio가 정의되기 전에도 현재 범위(함수 포함)에서 찾은 모든 변수를 표시할 수도 있습니다.

Start the debugger again (F5) and see that running the code stops on the line with that breakpoint. Here you can inspect the call stack and examine variables. Variables that are in-scope appear in the Autos window when they're defined; you can also switch to the Locals view at the bottom of that window to show all variables that Visual Studio finds in the current scope (including functions), even before they're defined:

5. Visual Studio 창 상단에 있는 디버깅 도구 모음(아래 표시)을 살펴보세요.

이 도구 모음을 사용하면 가장 일반적인 디버깅 명령(디버그 메뉴에서도 찾을 수 있음)에 빠르게 액세스할 수 있습니다.

Observe the debugging toolbar (shown below) along the top of the Visual Studio window. This toolbar provides quick access to the most common debugging commands (which can also be found on the Debug menu):

  1. The buttons from left to right as follows:
 
  1. Button
  1. Command
  1. Continue (F5)
  1. Runs the program until the next breakpoint or until program completion.
  1. Break All (Ctrl+Alt+Break)
  1. Pauses a long-running program.
  1. Stop Debugging (Shift+F5)
  1. Stops the program wherever it is, and exits the debugger.
  1. Restart (Ctrl+Shift+F5)
  1. Stops the program wherever it is, and restarts it from the beginning in the debugger.
  1. Show Next Statement (Alt+Num *)
  1. Switches to the next line of code to run. This is helpful when you navigate around within your code during a debugging session and want to quickly return to the point where the debugger is paused.
  1. Step Into (F11)
  1. Runs the next line of code, entering into called functions.
  1. Step Over (F10)
  1. Runs the next line of code without entering into called functions.
  1. Step Out (Shift+F11)
  1. Runs the remainder of the current function and pauses in the calling code.

6. Step Over를 사용하여 for 문을 한 단계씩 넘어갑니다.

단계별 실행은 디버거가 함수 호출을 포함하여 현재 코드 줄을 실행한 다음 즉시 다시 일시 중지함을 의미합니다.

코드에서 변수 i가 이제 Locals 및 Autos 창에 어떻게 정의되어 있는지 확인하세요.

Step over the for statement using Step Over. Stepping means that the debugger runs the current line of code, including any function calls, and then immediately pauses again. Notice in the code, how the variable i is now defined in the Locals and Autos windows.

7. make_dot_string을 호출하고 일시 중지하는 다음 코드 줄로 넘어갑니다.

여기서 Step Over는 특히 디버거가 make_dot_string 전체를 실행하고 반환될 때 일시 중지됨을 의미합니다.

별도의 중단점이 존재하지 않는 한 디버거는 해당 함수 내에서 중지되지 않습니다.

Step over the next line of code, which calls make_dot_string and pauses. Step Over here specifically means that the debugger runs the whole of make_dot_string and pauses when it returns. The debugger doesn't stop inside that function unless a separate breakpoint exists there.

계속해서 코드를 몇 번 더 실행하면서 Locals 또는 Autos 창의 값이 어떻게 변경되는지 관찰하세요.

Continue stepping over the code a few more times and observe how the values in the Locals or Autos window change.

Locals or Autos window에서 i 또는 s 변수의 값 열을 두 번 클릭하여 값을 편집합니다.

Enter 키를 누르거나 해당 값 외부의 영역을 선택하여 변경 사항을 적용합니다.

In the Locals or Autos window, double-click in the Value column for either the i or s variables to edit the value. Press Enter or select any area outside that value to apply any changes.

한 단계씩 코드 실행을 사용하여 코드를 계속 단계별로 실행합니다. Step Into는 디버거가 make_dot_string과 같은 디버깅 정보가 있는 함수 호출 내부로 들어간다는 것을 의미합니다. make_dot_string 내부에 들어가면 로컬 변수를 검사하고 코드를 구체적으로 단계별로 실행할 수 있습니다.

Continue stepping through the code using Step Into. Step Into means that the debugger enters inside any function call for which it has debugging information, such as make_dot_string. Once inside make_dot_string you can examine its local variables and step through its code specifically.

Step Into를 계속 진행하여 make_dot_string의 끝에 도달하면 다음 단계는 s 변수의 새 반환 값을 사용하여 for 루프로 반환됩니다. print 문으로 다시 한 단계씩 이동하면 인쇄 시 한 단계씩 실행이 해당 기능으로 들어가지 않는다는 점에 유의하세요. 이는 print가 Python으로 작성되지 않고 오히려 Python 런타임 내의 기본 코드이기 때문입니다.

Continue stepping with Step Into and notice that when you reach the end of the make_dot_string, the next step returns to the for loop with the new return value in the s variable. As you step again to the print statement, notice that Step Into on print doesn't enter into that function. This is because print isn't written in Python but is rather native code inside the Python runtime.

make_dot_string으로 다시 들어갈 때까지 한 단계씩 실행을 계속 사용하세요. 그런 다음 Step Out을 사용하여 for 루프로 돌아가는 것을 확인하세요. Step Out을 사용하면 디버거가 함수의 나머지 부분을 실행한 다음 호출 코드에서 자동으로 일시 중지됩니다. 이는 디버깅하려는 긴 함수의 일부를 단계별로 진행했을 때 유용합니다. 나머지 단계를 단계별로 진행하며 호출 코드에 명시적인 중단점을 설정하지 않습니다.

Continue using Step Into until you're again partway into make_dot_string. Then use Step Out and notice that you return to the for loop. With Step Out, the debugger runs the remainder of the function and then automatically pauses in the calling code. This is helpful when you've stepped through some portion of a lengthy function that you wish to debug. It will step through the rest and don't set an explicit breakpoint in the calling code.

다음 중단점에 도달할 때까지 프로그램을 계속 실행하려면 계속(F5)을 사용하십시오. for 루프에 중단점이 있으므로 다음 반복에서 중단됩니다.

To continue running the program until the next breakpoint is reached, use Continue (F5). Because you have a breakpoint in the for loop, you break on the next iteration.

수백 번의 루프 반복을 단계별로 진행하는 것은 지루할 수 있으므로 Visual Studio를 사용하면 중단점에 조건을 추가할 수 있습니다. 그런 다음 디버거는 조건이 충족되는 경우에만 중단점에서 프로그램을 일시 중지합니다. 예를 들어 i 값이 1600을 초과하는 경우에만 일시 중지되도록 for 문에 중단점이 있는 조건을 사용할 수 있습니다. 조건을 설정하려면 빨간색 중단점 점을 마우스 오른쪽 버튼으로 클릭하고 조건(Alt+F9 > C)을 선택합니다. . 나타나는 중단점 설정 팝업에서 표현식으로 i > 1600을 입력하고 닫기를 선택합니다. 계속하려면 F5를 누르고 다음 중단 전까지 프로그램이 많은 반복을 실행하는 것을 관찰하십시오.

Stepping through hundreds of iterations of a loop can be tedious, so Visual Studio lets you add a condition to a breakpoint. The debugger then pauses the program at the breakpoint only when the condition is met. For example, you can use a condition with the breakpoint on the for statement so that it pauses only when the value of i exceeds 1600. To set the condition, right-click the red breakpoint dot and select Conditions (Alt+F9 > C). In the Breakpoint Settings popup that appears, enter i > 1600 as the expression and select Close. Press F5 to continue and observe that the program runs many iterations before the next break.

프로그램을 완료할 때까지 실행하려면 여백의 점을 마우스 오른쪽 버튼으로 클릭하고 중단점 비활성화(Ctrl+F9)를 선택하여 중단점을 비활성화합니다. 그런 다음 계속을 선택하거나 F5를 눌러 프로그램을 실행합니다. 프로그램이 종료되면 Visual Studio는 디버깅 세션을 중지하고 편집 모드로 돌아갑니다. 또한 점을 선택하거나 점을 마우스 오른쪽 버튼으로 클릭하고 중단점 삭제를 선택하여 중단점을 삭제할 수도 있습니다. 또한 이전에 설정한 조건도 삭제됩니다.

To run the program to completion, disable the breakpoint by right-clicking the dot in the margin and selecting Disable breakpoint (Ctrl+F9). Then select Continue (or press F5) to run the program. When the program ends, Visual Studio stops its debugging session and returns to its editing mode. You can also delete the breakpoint by selecting its dot or by right-clicking the dot and selecting Delete breakpoint. It also deletes any condition you've previously set.

Tip

Python 인터프리터 자체 실행 실패와 같은 일부 상황에서는 출력 창이 잠시만 나타났다가 오류 메시지를 볼 기회 없이 자동으로 닫힐 수 있습니다. 이 경우 솔루션 탐색기에서 프로젝트를 마우스 오른쪽 단추로 클릭하고 속성을 선택하고 디버그 탭을 선택한 다음 인터프리터 인수 필드에 -i를 추가합니다. 이 인수를 사용하면 프로그램이 완료된 후 인터프리터가 대화형 모드로 전환되므로 Ctrl+Z > Enter를 눌러 종료할 때까지 창이 열린 상태로 유지됩니다.

In some situations, such as a failure to launch the Python interpreter itself, the output window may appear only briefly and then close automatically without giving you a chance to see any errors messages. If this happens, right-click the project in Solution Explorer, select Properties, select the Debug tab, then add -i to the Interpreter Arguments field. This argument causes the interpreter to go into interactive mode after a program completes, thereby keeping the window open until you enter Ctrl+Z > Enter to exit.

https://amzn.to/41nHjKZ

Next step

Install packages in your Python environment

Go deeper

 
반응형

댓글