skip to Main Content

I run a lot of scripts using VSCode interface and its launch configurations. Since my scripts all produce a lot of artefacts from running, it would be very useful to have an automated way to know if the script is running in debug mode (with F5 in vscode) as oposed to running without debugging (Ctrl+F5 in vscode), so that I could perform some cleanups at the beginning and end of the script’s run.

While I could set up a flag for debug mode in my configuration file, an automated way to identify it would be very useful because sometimes I or someone else running the scripts may forget to set the flag.

Is there some way to do that?

2

Answers


  1. You’re making the problem harder than necessary.
    Just define a wrapper, and ask VSC to debug that.

    def target():
        …
    
    def wrapper():
        cleanup1()
        target()
        cleanup2()
    
    Login or Signup to reply.
  2. In Visual Studio Code, you can determine if your script is running in debug mode or not by checking for specific environment variables that are set when a script is launched in debug mode. Here are a couple of methods to achieve this:

    Check for DEBUG Environment Variable

    When you run a script in debug mode (F5), VSCode sets certain environment variables. You can check for these variables in your script. For example, you can look for the NODE_ENV variable or any custom variable you set in your launch configuration.

    Example in Node.js:

    const isDebugMode = process.env.NODE_ENV === 'development' || process.env.DEBUG === 'true';
    
    if (isDebugMode) {
        console.log("Running in debug mode.");
        // Perform cleanup actions here
    } else {
        console.log("Running without debugging.");
        // Perform different actions here
    }
    

    Use the debug Module in Python

    If you’re using Python, you can check if the script is being run in debug mode by utilizing the sys module.

    Example in Python:

    import sys
    
    def is_debug_mode():
        return hasattr(sys, 'gettrace') and sys.gettrace() is not None
    
    if is_debug_mode():
        print("Running in debug mode.")
        # Perform cleanup actions here
    else:
        print("Running without debugging.")
        # Perform different actions here
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search