VS Code 高手秘籍:如何巧妙利用 Debug 參數提升開發效率

  • 在使用 Visual Studio Code(VS Code)進行腳本或應用程式開發時,設置中斷點來調試是一個非常方便的功能。然而,當你的腳本需要接受外部參數時,可能會發現 VS Code 的調試模式並不直接支持從外部傳入參數,這可能會讓開發過程變得有些不便。一個常見的解決方法是直接在腳本中硬編碼這些參數,但這樣做會使得程式碼顯得雜亂且不易於管理。
  • 幸運的是,VS Code 提供了一種方式來傳入這些外部參數而不需要修改原始程式碼。這可以通過配置 .vscode/launch.json 檔案來實現。在你的專案根目錄下的 .vscode 資料夾中(如果沒有,你需要手動創建),launch.json 檔案允許你定義多個調試配置,包括一個特別的 args 字段,用於指定需要傳入腳本的參數。
  • 要為你的應用程式或腳本添加調試參數,你只需要編輯 launch.json,在相應的配置中添加 args 陣列,並在其中填入你的參數。下面將一步一步教大家如何實現使功能

    step1:點擊 Add Configuration

    step2: 選擇 python debuger

    step3: 選擇 python File

    step4: 更改json file

    如果剛剛的步驟都正確的話,那麼就會順利的在隱藏資料夾.vscode裡面看到launch.json 檔案,下面將一個一個解釋各個參數的意義

各個參數解釋

  • name: 配置的名稱,這個名字會顯示在VS Code的調試啟動配置中,方便你選擇。這裡是”Python Debugger: Current File”,表示這是一個針對當前文件的Python調試配置。
  • type: 指定了調試器的類型。對於Python,通常是debugpy,這是一個流行的Python調試工具。
  • request: 指定調試會話的類型。**”launch”**表示啟動一個新的程序來進行調試。另一個選項是 **”attach”**,用於附加到一個已經運行的進程。
  • program: 指定要調試的Python程序的路徑。**${file}**是一個變量,它代表當前在VS Code中打開的文件。
  • console: 定義了調試輸出顯示的位置。**”integratedTerminal”**表示輸出會在VS Code的集成終端中顯示。
  • args: 一個字符串列表,定義了啟動調試的程序時要傳遞給它的參數。這裡的 **[“arg1”, “arg2”]**就是你程序啟動時會接收到的參數。

    原本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 Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}

後來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 Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"args": ["--flag", "--number","3","--string","test_string"]
}
]
}

step5:執行程序

import argparse

# Create the parser
parser = argparse.ArgumentParser(description='Example script with command line arguments')

# Add arguments
parser.add_argument('-f', '--flag', action='store_true', help='Flag argument')
parser.add_argument('-n', '--number', type=int, help='Number argument')
parser.add_argument('-s', '--string', type=str, help='String argument')

# Parse the arguments
args = parser.parse_args()

# Print all arguments
print(args)

執行畫面

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments