Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python in VS Code: Can I run cell in the integrated terminal?

In VS Code with Python, we can run a "cell" (block that starts with #%%) in the "Python Interactive Window"

Can we do the same thing on the Integrated Terminal?

I know we can do this in Spyder, where the terminal is generally always an IPython terminal

Matlab works in the same way with its terminal.

Can we do this in VS Code?

like image 587
Diogo Avatar asked Dec 31 '22 04:12

Diogo


1 Answers

I've opened a issue in GitHub, @AdamAL also opened, but it seems they don't have intention to do this. Here is a workaround to other users.

EDIT:

I've answered before with a workaround that takes 2 VSCode extensions and not use the smart command jupyter.selectCellContents.
@AdamAL shared a better solution using this command, but with the caveat that the cursor loses position and focusing only in Python terminal.
@Maxime Beau pointed that out expanding @AdamAL solution to the active terminal (that could be IPython, for instance)

Now I'm taking all answers and posting a general solution. This solution don't loose the cursor position when running only one cell. Also there's another command that runs the cell and advance to the next cell (as in Jupyter) and it is general to the active terminal (that could be IPython).

1. Install macros extension:

This extension have some additional commands that multi-command didn't have (like the delay command)

2. In settings.json

"macros.list": {
    "runCellinTerminal": [
        "jupyter.selectCellContents",
        "workbench.action.terminal.runSelectedText",
        "cursorUndo",
        {"command": "$delay","args": {"delay": 100}},
        {"command": "workbench.action.terminal.sendSequence","args": { "text": "\n" }},
    ],
    "runCellinTerminaladvance": [
        "jupyter.selectCellContents",
        "workbench.action.terminal.runSelectedText",
        "cursorDown",
        {"command": "$delay","args": {"delay": 100}},
        {"command": "workbench.action.terminal.sendSequence","args": { "text": "\n" }},
    ],
}

OBS: cursorUndo takes the cursor back to the right position. cursorDown takes the cursor to the next cell. The commands delay and sendSequence \n are usefull when the terminal is an IPython terminal.

3. In keybinding.json:

{
    "key": "ctrl+alt+enter",
    "command": "macros.runCellinTerminal",
    "when": "editorTextFocus && jupyter.hascodecells"
},
{
    "key": "shift+alt+enter",
    "command": "macros.runCellinTerminaladvance",
    "when": "editorTextFocus && jupyter.hascodecells"
},
like image 124
Diogo Avatar answered Jan 14 '23 03:01

Diogo