2

I'm writing Python in VS Code and can't seem to find a solution to this.

I want a shortcut key that always runs my main project file that contains "main()"

Everything I've found so far just runs the current editor file and it gets old fast having to switch back to the file every time.

Dave
  • 1,696
  • 4
  • 23
  • 47
  • Take a look at this: https://stackoverflow.com/questions/29987840/how-to-execute-python-code-from-within-visual-studio-code – Joseph Holland Aug 30 '19 at 07:13
  • I know how to execute code. What I don't know is how to automatically execute my project's "main" file instead of the current module open in the editor. – Dave Aug 30 '19 at 07:21
  • the first answer in that post details setting up a custom task to run **any** project file by adding it to tasks.json, then run it with `CTRL` + `SHIFT` + `B` – Joseph Holland Aug 30 '19 at 07:25
  • If you scroll down it states in another answer that "All these answers are obsolete now." The answer you mention is from 2015 and things have changed significantly since then. – Dave Aug 30 '19 at 07:42
  • bugger, my bad. – Joseph Holland Aug 30 '19 at 07:46
  • What is the command you wish to run? `python ....what` specifically? – Mark Aug 30 '19 at 14:27

2 Answers2

1

If you just want a keybinding to run something in the terminal, try:

{
    "key": "alt+x",                                      // whatever keybinding you choose
    "command": "workbench.action.terminal.sendSequence",
     //  "args": {"text": "python ${file}\u000d"}
     "args": {"text": "python MyFileName\u000d"}
}

${file} would always run the current file, which you do not want so replace ${file} with your filename that you do want to run.

\u000d is a return so it runs immediately.

See send text to terminal with a keybinding. In addition to a hard-coded reference to some filename, you can also use vscode's variables.

Mark
  • 143,421
  • 24
  • 428
  • 436
0

Create the following launch configuration (change MyMain.py to your main file)

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Main File",
      "type": "python",
      "request": "launch",
      "program": "${workspaceFolder}/MyMain.py",
      "console": "integratedTerminal",
      "cwd": "${workspaceFolder}"
    }
  ]
}
rioV8
  • 24,506
  • 3
  • 32
  • 49