Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Python console in a VScode

recently I switched from Spyder to VScode and I miss getting the output of python scripts in console. By that I mean: Let's say I have a script as follow:

x = []
def append_func(x):
   for i in range(10):
      x.append(i)
   return x

y = append_func(x)

and when I ran that script in Spyder, x would be generated, append_func would be declared and y would be generated as well. Then in console (outside of the script) I would write:

sum(y)
len(x)
len(y)

and get informations that may interest me after running the script.

So I would like play with my variables that were generated inside the script without editing the script and rerunning it. Similar functionality is in Matlab - whenever we run the script, all of the variables and functions defined in a script are accessible in console, so we can transform/calculate/reuse them, check how some variables look like or what are their types, (...). It's very handy when the scripts has kinda long execution time and we want to check some statistics of variables we didn't think about before.

Is such functionality in VS Code? Screen from Spyder. As we can see x and y got saved into memory and can be used in the console:

enter image description here

like image 542
Saguro Avatar asked Sep 06 '25 03:09

Saguro


1 Answers

Please use the python interactive. There are two ways in vscode, one is terminal and the other is window.

Right-click and select Run Current File in Interactive Window to open an interactive window and run the current script. You can continue to enter python code in the input box below and execute it with Shift+Enter.

enter image description here

Or use Shift+Enter to open a python interactive terminal, then select all the code in the file and press Shift+Enter to run code in the terminal, then you can continue to type python code and press Enter to execute.

enter image description here

If you want to look at the variables, clicking Variables in the interactive window will open a variables panel for you to look at.

enter image description here

There are more detailed instructions in the official documentation.

In addition, as you can see, there is a shortcut key conflict by default. If you want to use the shortcut key Shift+Enter to open an interactive window, you need to modify the corresponding shortcut key settings.

enter image description here

like image 88
JialeDu Avatar answered Sep 07 '25 21:09

JialeDu