简体   繁体   中英

Detect Python Is Running In Visual Studio Code

There are cases where code needs to act differently if running in Visual Studio Code.

Does anybody know the most efficient way to detect that the python code is running in the Visual Studio Code debugger?

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.

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

'not vscode'

if you call python myscript.py --vscode

'vscode'

Then you can just add a run task in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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