Massimiliano Kraus
Massimiliano Kraus

Reputation: 3833

How to create a VS Code's task to execute the current file, setting also its folder as the current working directory?

I'm experimenting with many little projects at once, with one single VS Code window open on the root folder.

They could be JS projects or Python ones, or others runnable through terminal commands.

I want to create a VS Code task that:

1) starts the program on the file currently open and focused;

2) set the current working directory to the directory of that file.

That must happen dynamically, i.e. I don't want to set the current file and the current working directory manually every time I want to start a different file.

How can I achieve that?

Upvotes: 1

Views: 2846

Answers (1)

Massimiliano Kraus
Massimiliano Kraus

Reputation: 3833

You can use the variables ${fileDirname} and ${file} in the tasks.json file.

Let's say you're experimenting with Python.

Here are two solutions:

"tasks": [
    {
        "label": "start",
        "type": "shell",
        "command": "python3 ${file}",
        "options": {
            "cwd": "${fileDirname}"
        }
        "problemMatcher": []
    }
]

OR

"tasks": [
    {
        "label": "start",
        "type": "shell",
        "command": "cd ${fileDirname} && python3 ${file}",
        "problemMatcher": []
    }
]

Upvotes: 10

Related Questions