Skip to content

tasks.json: Assign Keyboard Shortcuts to Run Python as Module in VSCode / Cursor IDE

Source: Notion | Last edited: 2024-11-05 | ID: 11e2d2dc-3ef...


2024-11-03 compatible with bash and zsh scripts

2024-11-02 script updated; previously only compatible with macOS but now also with Linux

This tasks.json configuration file below is designed to enhance your development workflow in Visual Studio Code / Cursor IDE by allowing you to run Python files as modules directly from the editor. It leverages the “Command Variable” extension by rioj7 to dynamically convert file paths to module notation, making it easier to execute Python scripts in a modular fashion.

Please follow the instructions in the comments to install.

{
// Extension Requirement:
// - This task requires the "Command Variable" extension by rioj7.
//
// Installation instructions for `tasks.json`:
// 1. Create a `.vscode` folder in your project's root directory if it doesn't exist.
// 2. Inside the `.vscode` folder, create a file named `tasks.json`.
// 3. Copy the entire contents of this code snippet into your `tasks.json`.
// 4. Save the file.
//
// Activate tasks via Command Palette (more steps):
// - Use the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) and type 'Tasks: Run Task' to select and run a task.
//
// Activate tasks via keyboard shortcuts (less steps):
// - To assign keyboard shortcuts to open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P),
// you'd see `Preferences: Open Keyboard Shortcuts (JSON)` in the list, select it,
// you'd see the `keybindings.json` file open in the editor,
// then add the following entries:
// {
// "key": "cmd+3",
// "command": "workbench.action.tasks.runTask",
// "args": "Run Current Python File as Module"
// },
// {
// "key": "alt+cmd+3",
// "command": "workbench.action.tasks.runTask",
// "args": "Run Current Python File as Module (New Terminal)"
// },
// {
// "key": "alt+cmd+4",
// "command": "workbench.action.tasks.runTask",
// "args": "Run Current Shell Script",
// "when": "editorTextFocus && editorLangId == 'shellscript'"
// },
// {
// "key": "alt+cmd+5",
// "command": "workbench.action.tasks.runTask",
// "args": "Smart Run Current File (New Terminal)"
// }
//
// Task Descriptions:
// 1. "Run Current Python File as Module": Executes Python files as modules with:
// - Automatic PYTHONPATH configuration
// - Module path transformation
// - Shared terminal panel
//
// 2. "Run Current Python File as Module (New Terminal)": Identical functionality as above but:
// - Spawns dedicated terminal instance
// - Appends newline for clarity
//
// 3. "Run Current Shell Script": Executes shell scripts with diagnostics:
// - Validates executable permissions
// - Displays execution metadata
// - Supports bash/zsh detection
// - Provides execution boundaries
//
// 4. "Smart Run Current File (New Terminal)": Universal executor that:
// - Solicits file type (.py, .sh, .zsh)
// - Executes Python via module notation
// - Manages shell script permissions
// - Provides failure feedback
"version": "2.0.0",
"tasks": [
{
"label": "Run Current Python File as Module",
"type": "shell",
"command": "python -m \"$(echo '${input:getFullModulePath}' | sed 's:^[/.]\\+::' | tr '/' '.')\"",
"options": {
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${workspaceFolder}"
}
},
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"echo": false,
"reveal": "always",
"focus": true,
"panel": "shared",
"showReuseMessage": false,
"clear": false,
"revealProblems": "onProblem",
"close": false
},
"problemMatcher": [],
"detail": "Runs the current Python file as a module.",
"promptOnClose": false
},
{
"label": "Run Current Python File as Module (New Terminal)",
"type": "shell",
"command": "python -m \"$(echo '${input:getFullModulePath}' | sed 's:^[/.]\\+::' | tr '/' '.')\" && echo",
"options": {
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${workspaceFolder}"
}
},
"group": "build",
"presentation": {
"echo": false,
"reveal": "always",
"focus": true,
"panel": "new",
"showReuseMessage": false,
"clear": false
},
"problemMatcher": [],
"detail": "Runs the current Python file as a module in a new terminal instance."
},
{
"label": "Run Current Shell Script",
"type": "shell",
"command": "clear && echo \"🎯 SHORTCUT TEST: alt+cmd+4 was pressed!\"; echo \"📍 Current timestamp: $(date)\"; echo \"📂 Attempting to process: ${file}\"; if [ -x \"${file}\" ]; then echo \"✅ File is executable\"; else echo \"⚠️ File permissions check: $(ls -l \"${file}\")\"; echo \"🔧 Setting executable permission...\"; chmod +x \"${file}\"; fi; echo \"▶️ Executing script now:\"; echo \"====================\"; case \"${file}\" in *.zsh) zsh \"${file}\";; *) bash \"${file}\";; esac; echo \"====================\"; echo \"✅ Script execution completed\"",
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"presentation": {
"echo": false,
"reveal": "always",
"focus": true,
"panel": "new",
"showReuseMessage": false,
"clear": true,
"close": false,
"revealProblems": "onProblem"
},
"problemMatcher": [],
"detail": "Debug version: Runs shell script with verbose output"
},
{
"label": "Smart Run Current File (New Terminal)",
"type": "shell",
"command": "if [[ \"${file}\" == *.py ]]; then python -m \"$(echo '${input:getFullModulePath}' | sed 's:^[/.]\\+::' | tr '/' '.')\" && echo; elif [[ \"${file}\" =~ \\.(sh|zsh)$ ]]; then chmod +x \"${file}\" 2>/dev/null; case \"${file}\" in *.zsh) zsh \"${file}\";; *) bash \"${file}\";; esac; else echo \"⚠️ Unsupported file type: ${file}\"; fi",
"options": {
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${workspaceFolder}"
}
},
"group": "build",
"presentation": {
"echo": false,
"reveal": "always",
"focus": true,
"panel": "new",
"showReuseMessage": false,
"clear": true,
"close": false
},
"problemMatcher": []
}
],
"inputs": [
{
"id": "getFullModulePath",
"type": "command",
"command": "extension.commandvariable.transform",
"args": {
"text": "${relativeFileDirname}/${fileBasenameNoExtension}",
"find": "^\\./+",
"replace": "",
"flags": "g"
}
},
{
"id": "getFullScriptPath",
"type": "command",
"command": "extension.commandvariable.file.absolutePath"
}
]
}