Home > front end >  VSCODE how to create a custom command linked to a shortcut : Run Active python file in **Active or S
VSCODE how to create a custom command linked to a shortcut : Run Active python file in **Active or S

Time:03-30

In VsCode I am trying to find how i can :

  • Run ACTIVE python file in ACTIVE terminal

Note: I already have a key binding to "Run active file in active terminal" but i does not include the python interpreter path/keyword before launching the command so it is just opening the file)

I know there are multiple ways to run python file in terminal (F5 for debug etc...) and "Shift Enter" works quite well if you do not have to deal with location of the running file.

In this case when "Shift Enter", I would like to "cd my/project/folder/where/my/file/is" and then "python3 myFileToRun.py", so having a terminal opened at the file's location will allow me to quickly hit the shortcut without any locations issues.

I tried to figure out how are the 'commands' from VsCode working but did not find much info. Already tried a mix of two commands in the keybinding.json but no results:

{
    "key": "shift enter",
    "command": "-python.execSelectionInTerminal",
    "when": "editorTextFocus && !findInputFocussed && !jupyter.ownsSelection && !notebookEditorFocused && !replaceInputFocussed && editorLangId == 'python'"
},
{
    "key": "shift enter",
    "command": "-workbench.action.terminal.findNext",
    "when": "terminalFindFocused && terminalProcessSupported"
},
{
    "key": "shift enter",
    "command": "-python.execSelectionInTerminal",
    "when": "terminalFindFocused && terminalProcessSupported"
},

CodePudding user response:

in response to @rioV8

Here is how my directories look likes in VSCode and what behavior i would like.

  • Is it the good location ?
  • Can i put the launch.json in the .vscode at the ROOT ?
  • Do i have to create a separate keybindings.json to put at the location of the launch.json?
ROOT "where terminal prompt start when hit shift enter"
|
|____.vscode
|           |_____settings.json
|
|____FOLDER1
            |_____FOLDER2
                         |____.vscode
                         |          |_launch.json
                         |
                         |_myPythonFile.py "where i want my terminal to open"

CodePudding user response:

  • Create a Task to run the current Python file

.vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Current File",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal",
      "cwd": "${fileDirname}"
    }
  ]
}
  • Create a keybinding to execute this Task

keybindings.json

  {
    "key": "shift enter",
    "command": "workbench.action.tasks.runTask",
    "args": "Python: Current File",
    "when": "editorTextFocus && editorLangId=='python'"
  }
  • Related