[英]Detect Python Is Running In Visual Studio Code
在某些情況下,如果在 Visual Studio Code 中運行,代碼需要采取不同的行為。
有人知道檢測 python 代碼正在 Visual Studio Code 調試器中運行的最有效方法嗎?
到目前為止,我能找到的最好方法是使用:
import sys
if 'debugpy' in sys.modules:
print("Running in VS Code")
我認為解決這個問題最優雅的方法就是在 vscode 中設置一個運行任務,該任務運行帶有額外命令行標志的 Python 腳本。
例如:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--vscode', action='store_true')
args = parser.parse_args()
if args.vscode:
print("vscode")
else:
print("not vscode")
那么如果你調用腳本python myscript.py
'不是vscode'
如果你調用python myscript.py --vscode
'vscode'
然后你可以在 vscode 中添加一個運行任務:
{
"label": "run",
"command": "python", // or python3
"group": {
"kind": "test",
"isDefault": true
},
"args": [
"${file}",
"--vscode"
],
"presentation": {
"echo": true,
"panel": "shared",
"focus": true
},
"problemMatcher": []
}
要運行您的代碼,只需使用運行任務的快捷方式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.