當我在另一個腳本匯入的函式中設定斷點時,我希望能夠從 VS Code Python 除錯控制臺中查看父范圍內的變數。這可能嗎,也許通過修改launch.json?
可重現的例子:
我有兩個檔案,scratch_script.py和scratch_function.py. 它們存在于同一目錄中。
我在下面的評論指示的地方放置斷點。
內容scratch_script.py:
import scratch_function
parent_scope_var = 'I disappear'
scratch_function.scratch_function() # breakpoint on this line
pass # breakpoint on this line
內容scratch_function.py:
def scratch_function():
child_scope_var = 'I appear'
pass # breakpoint on this line
我從scratch_script.py.
在第一個斷點處,我可以parent_scope_var在 Python 除錯控制臺中查看,但不是child_scope_var. 到目前為止,一切都很好。
當我進行到第二個斷點時,我可以查看child_scope_var,這很棒。但現在我無法查看parent_scope_var:
NameError: name 'parent_scope_var' is not defined
在第三個斷點上,parent_scope_var在 Python 除錯控制臺中再次看到了 ,但沒有看到child_scope_var... 這是我所期望的。
parent_scope_var所以,我唯一的困惑是,為什么在被呼叫函式的斷點處暫停時無法查看?變數仍然存在,對嗎?只是在父范圍內?
uj5u.com熱心網友回復:
是的,因為當你除錯到第二個斷點時,python 會執行呼叫函式。此時,python將打開該scratch_function.py檔案。
第一個斷點:

第二個斷點:

它只會顯示當前檔案中存在的parent_scope_var變數,而檔案中沒有變數scratch_function.py,python解釋器找不到parent_scope_var,所以watch面板提示錯誤:NameError: name 'parent_scope_var ' is not defined.

但正如您可能猜到的那樣,該變數此時仍然存在,就在scratch_script.py檔案中。此時可以打開scratch_script.py檔案,將滑鼠懸停在parent_scope_var變數上,此時vscode會清晰的顯示變數值。

附帶說明一下,您還可以在CALL STACK面板中看到上一個parent_scope_var變數。

PS:除錯時在代碼檔案中行內顯示變數值的設定:
//file:settings.json
{
"debug.inlineValues": "on",
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/492166.html
標籤:Python 调试 视觉工作室代码 vscode 调试器
上一篇:Camel應用程式從哪里開始?
