简体   繁体   English

检测 Python 正在 Visual Studio Code 中运行

[英]Detect Python Is Running In Visual Studio Code

There are cases where code needs to act differently if running in Visual Studio Code.在某些情况下,如果在 Visual Studio Code 中运行,代码需要采取不同的行为。

Does anybody know the most efficient way to detect that the python code is running in the Visual Studio Code debugger?有人知道检测 python 代码正在 Visual Studio Code 调试器中运行的最有效方法吗?

So far, the best way I could find was using:到目前为止,我能找到的最好方法是使用:

import sys
if 'debugpy' in sys.modules:
    print("Running in VS Code")

I think the most elegant way to solve this is just to set up a run task in vscode that runs the Python script with an extra command line flag.我认为解决这个问题最优雅的方法就是在 vscode 中设置一个运行任务,该任务运行带有额外命令行标志的 Python 脚本。

for example:例如:

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")

then if you call the script python myscript.py那么如果你调用脚本python myscript.py

'not vscode' '不是vscode'

if you call python myscript.py --vscode如果你调用python myscript.py --vscode

'vscode' 'vscode'

Then you can just add a run task in vscode:然后你可以在 vscode 中添加一个运行任务:

{
    "label": "run",
    "command": "python", // or python3
    "group": {
        "kind": "test",
        "isDefault": true
    },
    "args": [
        "${file}",
        "--vscode"
    ],
    "presentation": {
        "echo": true,
        "panel": "shared",
        "focus": true
    },
    "problemMatcher": []
}

To run your code, just use a shortcut for your run task要运行您的代码,只需使用运行任务的快捷方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM