Search code examples
visual-studio-codevscode-tasks

Is there a way to run launch.json and tasks.json in same terminal in VSCode?


I am new to VSCode and recently came across launch.json and tasks.json that are super handy for automation and setups.

So I wanted to build a setup that does following :

  1. Export some configs from a config file config.sh using tasks.json
  2. Run python tests using launch.json templates

I have created a launch.json that contains below code to run my automation :

{
    "name": "Python: Current File",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "justMyCode": true,
    "preLaunchTask": "Export Configs"
}

Above launch.json contains a preLaunchTask which I have added in tasks.json as below:

{
    "label": "Export Configs",
    "type": "shell",
    "command": "bash",
    "args": [
        ".vscode/configs.sh"
    ],
    "group": {
        "kind": "build",
        "isDefault": true
    },
    "presentation": {
        "reveal": "always",
        "focus": true,
        "panel": "shared",
        "close": false
    }
}

configs.sh contains below code :

#!/bin/bash
export CONFIG_VALUE=1234

I am trying to run python test file which prints value of CONFIG_VALUE parameter.

Now when I debug my test file using the launch.json config, it exports CONFIG_VALUE successfully. But when the test runs, it is not able to read value of CONFIG_VALUE.

Issues I think that might be causing this :

  1. tasks.json and launch.json and executed in different terminals and hence not able to use variables.
  2. Also I am using poetry environment where variables are not getting exported to.

Any help is highly appreciated. Thanks in advance.


Solution

  • You don't need to create a preLaunchTask to read environment variables. Just use the env property.

    {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Python: Current File",
                "type": "python",
                "request": "launch",
                "program": "${file}",
                "console": "integratedTerminal",
                "justMyCode": true,
                "env": {
                    "CONFIG_VALUE": "HELLO WORLD"
                }
            },
            {
                "name": "Launch 2: Current File",
                "type": "python",
                "request": "launch",
                "program": "${file}",
                "console": "integratedTerminal",
                "justMyCode": true,
                "env": {
                    "CONFIG_VALUE": "Bonjour monde!" // different value
                }
            },
    
        ]
    }
    

    Your python program should be able to read the environment variable

    import os
    
    my_env_var = os.environ['CONFIG_VALUE']
    print(my_env_var) # outputs "HELLO WORLD"
    

    enter image description here