Sending code snippets to the debug console interpreter - python

I'd like to send code I have selected from the editor to the interpreter running in the debugging console during an active debugging session. Can I do this in VSCode? If so, how?
Update 1
While Mark (accepted answer) provided what seems to be the right command (it works for me from the contextual menu with the mouse), this isn't working for me yet as a keyboard binding, and I reported this issue here.
Update 2
This started working again as of April 21, 2020 (latest Insiders version).

See https://code.visualstudio.com/docs/python/editing#_run-selectionline-in-terminal-repl
Run Selection/Line in Terminal (REPL)
The Python: Run Selection/Line in Python Terminal command
(Shift+Enter) is a simple way to take whatever code is selected, or
the code on the current line if there is no selection, and run it in
the Python Terminal. An identical Run Selection/Line in Python
Terminal command is also available on the context menu for a selection
in the editor.
VS Code automatically removes indents based on the first non-empty
line of the selection, shifting all other lines left accordingly.
Source code that runs in the terminal/REPL is cumulative until the
current instance of the terminal is closed.
The command opens the Python Terminal if necessary; you can also open
the interactive REPL environment directly using the Python: Start REPL
command. (Initial startup might take a few moments especially if the
first statement you run is an import.)
On first use of the Python: Run Selection/Line in Python Terminal
command, VS Code may send the text to the REPL before that environment
is ready, in which case the selection or line is not run. If you
encounter this behavior, try the command again when the REPL has
finished loading.
And see Use IPython REPL in VS Code for info about the IPython REPL.
--------- generic info for other languages -------------------------------------------------------------
It sounds like you want to send it the repl. There is an unbound command:
editor.debug.action.selectionToRepl
which will send selected text to the debug repl.
{
"key": "alt+y", // whatever you want here
"command": "editor.debug.action.selectionToRepl"
},

No, you cannot send a selection of code to the debugger. You need to debug the whole file or use the Interactive Window support to debug a specific cell.

Related

VSCode Jupyter: is there a way to make python interactive window work as default console?

I've recently switched to VSCode, and am wondering if there's a way to make the Python Interactive Window from the Jupyter support in VSCode work like the console in Spyder where I just have to select code and press ctrl+enter to send it, without having to create cells everytime.
For now I'm resigned to work with the Terminal until my code is clean and then create a cell when I have reusable code, and would like to just work directly with the PIW.
You can always change the default console setting by:
Opening the Command Palette (⇧⌘P)
Typing "Preferences:Open Settings (JSON)
Edit this line:
"python.dataScience.sendSelectionToInteractiveWindow": false
You should be able to do this with the latest python extension. The select the code you want to execute and press shift-enter. Is that not working?
For me (now) interactive mode runs after setting "jupyter.sendSelectionToInteractiveWindow": true
#FranciscoRZ. You should have seen a popup option for this, but if it didn't come up for you it can just be manually set in VSCode options. Just change this guy here:
Python->Data Science: Send Selection To Interactive Window
That should get you what you are looking for.
OP's Note: Accepting this answer because it will be the right anwser starting with the February release of VS Code Python
If you have the notebook saved as a python percentage script (which is more git friendly)
each "cell" will be delimited by # %% and the default run command is "Shift+Ctrl".
Later once you are working in the interactive window, If you want a particular cell you wrote on the fly to be in you script, there is one button which says "Paste code into file" right next to the recently executed cell in the interactive window.
And in case you are using the notebook for the sake of being able to later export it to html or pdf, once executed in the interactive window, there is an export button as well.

In VS Code, can one run Python code in an integrated Python terminal like in Spyder?

Currently, in Visual Studio Code (under Windows 10 64bits), at a Python file called path\myfile.py, if one clicks with mouse right-button for context menu and then chooses 'Run Python File in Terminal', an integrated CMD terminal is open and file is automatically run there with:
python.exe path\myfile.py
After the file stops running, one is naturally left at the integrated CMD cursor.
This behavior is quite different, for instance, from what one has with an IDE like Spyder. There, when you run code (e.g. with F5), at the end one is left still at the Python cursor and can access content of variables created when code was run.
Is there a way to achieve a similar behavior in Visual Studio Code?
You can configure VS Code Python extension to use the -i command line option
Described in https://docs.python.org/3/using/cmdline.html#cmdoption-i
You only have to add the setting bellow (inside settings.json file)
"python.terminal.launchArgs": ["-i"],
This will execute the command python.exe -i path\myfile.py.
I don't know if it is a new feature, but I've been using it for while.
If you would like to use the terminal IPython, like in Spyder, you can use a different set of options, as the following:
"python.terminal.launchArgs": ["-m","IPython","-i"],
With these, VS Code will execute the command python.exe -m IPython -i path\myfile.py.
Then, it will run IPython module as a "script" (with -m option), which will use the options -i path\myfile.py, i.e., IPython will run the file and remain opened.
BTW, another thing is: you can run "cells" in Spyder's integrarted terminal (regions of code with #%%). But in VS Code it seems you can't.
I've made a question with a "work around" to run cells of Python files in VS Code Integrated terminal, which is posted Here
Yes. Open a terminal window and it's like a terminal window on your computer. You can type python filepathandname and the python script will execute like it does from the command line.
The closest you can come is to run the code under the debugger and set a breakpoint at the end to pause the exiting of the execution. Otherwise feel free to file a feature request at https://github.com/microsoft/vscode-python.

Visual Studio Code - python console

I'm using visual studio code with standard python extension, my issue is that when I run the code the python interpreter instantly closes right after and I only see the output which means that if I create some data structure I have to create it every single time. Is it possible to leave the console open after running the code and maybe running multiple files in the same python interpreter instance?
I used to use spyder which is entirely doing what you want (probably like PyCharm)...
Then I briefly tried VS Code, and it is quite easy to make it behave that way too.
First make sure you have an integrated terminal open (or do Ctrl+`, or View > Integrated Terminal), then in that terminal launch ipython.
Now, when you use the commands from Don Jayamanne's Python extension (Ctrl+Shift+P to open commands palette):
"Run Python File in terminal"
"Run select/line in Terminal"
It will run the line inside the ipython console directly. So running the entire file will call python module.py inside ipython, and thus fails.
So to make this work simply create settings to map which command is executed when "Run select/line in terminal":
Open Language specific settings (Shift+Ctrl+P, search "Configure Language specific Settings...")
Pick up Python
Now I would suggest to make change only in your workspace settings (top-right tab) to keep default behaviour in other cases
so add in WORKSPACE SETTINGS:
(keep in mind it is just a simple/stupid workaround)
{
"python.pythonPath": "run"
}
Now when runing whole file, it will use ipython function run within the ipython terminal that we launched, thus keeping all your workspace variables.
Also, if you run some line of code with "Run Select/Line in Terminal", the ipython session of that terminal keep all variables.
This allows live debugging, without actually going in the debug mode.
When you run a program, it runs until it ends. Then it closes. If you want it to stay live longer, you can make a program which does not stop until told so, e.g.
while True:
something = raw_input('Write something: ')
print('You wrote: %s' % something)
if something == 'bye':
print 'bye.'
break
This will run until user writes "bye".
I'm quite late to this conversation, but a workaround I use is to put a pass statement at the end of my file, then add a breakpoint to it. I then run it in the debugger and can access all of the variables etc.
This allows most of the functionality that I used to use in the PyCharm python terminal, such as exploring data structures, checking out methods, etc. Just remember that, if you want to make a multi-line statement (eg. for a loop), you need to use Shift-Enter to go to the next line otherwise it'll try to evaluate it immediately.

Difference Between Python's IDLE and its command line

What are the key differences between Python's IDLE and its command line environment? IDLE looks nicer, of course, and has some kind of GUI...
Moreover, is IDLE treated the same as the shell? I mean, the shell is the middle layer between the user and Python's interpreter?
They are both the same thing but, IDLE is made to write python code so its better if you can to write on IDLE. You can also try Notepad++ its a pretty good program to write code on.
I am not sure what you question is, but here is a Windows-7 oriented answer of similarity and difference. In the start menu for Python x.y, you can select 'Python x.y (x bits)' to run python interactive in a text-line-oriented console window provided by Microsoft. The console handles key presses and mouse movements and clicks. When you hit , the console sends the line of text to python, which is waiting for input on sys.stdin. When Python processes the line, it sends output to sys.stdout or sys.stderr. This includes '>>> ' and '... ' prompts. The console displays the text for you to see.
In the start menu, you can instead select 'Idle ...'. Unless you have previously selected a different startup option, python run Idle code which uses the tkinter module which used tcl/tk to run a graphical user interface that somewhat imitates the console. The tkinter/tk gui handles key and mouse input and displays output. In both cases, some software besides the Python interpreter itself handles interaction between you and Python.
Some important differences:
Cut, copy, and paste work normally. The Windows console is crippled in this respect.
Idle colors input and output. The Windows console does not.
Idle can display all unicode BMP (the first 64K) chars. The Windows console is limited by code pages.
For 1, 2, and 3, the console of other OSes may do as well or better than Idle.
Idle lets you enter, edit, send, and retrieve complete statements. Interactive python with Windows console only works with physical lines.
Update, 2017/11:
Item 1 above: At least on current Win10, cut, copy, and paste work normally.
Item 3 above: At least on Win10, unicode works better in Command Prompt with 3.6+.
New item 5: The IDLE doc section, also available as Help => IDLE Help now has section '3.3. IDLE-console differences'.
IDLE is a very simple Integrated Development Environment. It runs the same python, libraries etc. as commant-line.
Even more basic (with less features) is IPython. Full feature IDE for Python is, for example, Eclipse with PyDev plugin, or LiClipse.
Python IDLE is where you write your program/s and Python Shell is where you run your program/s.

Running code in PyCharm's console

Are there any smooth way to run Python scripts in the PyCharm's console?
My previous IDE - PyScripter - provides me with that nice little feature. As far as I know PyCharm has 2 ways of running script in console:
1) Select a bunch of code and press Ctrl+Alt+E.
2) Save the code in a file and import it from the Console.
Are the any way to do it by pressing "Run" or "Debug" buttons? I need to see the result of my script in the console and all variables available to manipulate.
In the Run/Debug Configuration, add -i to the interpreter options. This will stop it from closing a python session even after a successful run. I.e. you will be able to see all the variable contents
Run -> Edit configuration -> select the script you want to run and give it a display name -> OK
Now you can run it with the green "Run" button. The green bug button (next to the run button) will run it in debug mode.
Remark: next to the run button you can monitor the script/configuration you run by selecting it's display name.
If you create run-time configuration then after pressing the run button (green "play" icon) you will get the desired result: your code will give you output in a console which opens atomatically at the bottom.
You can create many different configuraions for run and debug within a single project.
Here is a link from PyCharm's web help which covers the run/debug configurations:
http://www.jetbrains.com/pycharm/webhelp/run-debug-configuration-python.html
A possible way of manipulating the variables using debug mode and evaluate expression window is added in comment but I missed one detail: to see the result of your interactive code execution you have to switch from Debugger to Console output; mode tabs are on the top-left side of the bottom pane.
The way I do it is a create my script in the editor, call it myfirst.py, eg
print "Hello"
a= 1234
then in the console I run:
reload (myfirst)
To check on the variables use:
>>> myfirst.a
Not perfect but that's pyCharm for you. If you want a pyScripter like experience which I think is more useful you can try spyder2.
It may also be a good option for you to use the magic command
%run scriptname.py
in the ipython console (including the %-character). Compared to Cntrl + Alt + E you also get clean information on errors in your code.
Due to autocomplete it's also typed in a second and you can use this in any environment with an ipython shell. For me as a scientist who often uses python to explore data, this is a good option.
With your program in the editor:
Run - Edit Configurations
Then under Execution check the box for "Run with Python console".
When you run the program from the green arrow it will run in a console. After the run all your objects are available to examine and play with.

Categories

Resources