I'm using visual studio code with DonJayamanne python extension. It's working fine but I want to have an interactive session just like the one in Matlab, where after code execution every definition and computational result remains and accessible in the console.
For example after running this code:
a = 1
the python session is terminated and I cannot type in the console something like:
b = a + 1
print(b)
I'm aware that the python session can stay alive with a "-i" flag. But this simply doesn't work.
Also every time I run a code file, a new python process is spawned. Is there a way to run consecutive runs in just one console? Again like Matlab?
This sounds really essential and trivial to me. Am I missing something big here that I can't find a solution for this?
I'm the author of the extension.
There are two options:
Use the integrated terminal window (I guess you already knew this)
Launch the terminal window and type in python.
Every statement executed in the REPL is within the same session.
Next version will add support for Jupyter.
Please have a look here for some samples of what is yet to come:
#303
Screen samples and more
I added the following lines into user setting file, then it works.
Select some lines of python code, then right-click and select Run selected code in python terminal
Solution 1: Will start iPython terminal
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
"terminal.integrated.shellArgs.windows": ["/K ipython"],
Solution 2: Will start a terminal like "python -i"
"python.terminal.launchArgs": ["-i"],
The following line will solve your problem.
"python.terminal.launchArgs": ["-c","\"from IPython import embed; embed()\""]
Related
I just started a python bootcamp and am using Microsoft Visual Studio Code (latest version with Python 3.10.5) but have a couple of questions. (apologies for the long post)
I have the following code:
def weather_condition(temperature):
if temperature > 7:
return "Warm"
else:
return "Cold"
input("What temperature: ")
To my knowledge there are three options to run the code
Right mouse click and 'run python file in terminal
Select lines and press SHIFT + ENTER
RUN (with or without debugging)
However even though the script is the same, each choice shows a complete different result in the terminal.
If I choose to run the python file, it shows the following error in the terminal:
terminal error message
>>> & C:/Users/..../AppData/Local/Microsoft/WindowsApps/python3.10.exe d:/..../_SCRIPTING_/Python/Python001/user_input2.py
File "<stdin>", line 1
& C:/Users/fine/AppData/Local/Microsoft/WindowsApps/python3.10.exe d:/..../_SCRIPTING_/Python/Python001/user_input2.py
^
SyntaxError: invalid syntax
If I choose select lines (same lines used as #1),
selected lines
it runs the script but it displays the entire script run process in the terminal (which doesnt happen on the teacher's visual code:
mine:
>>> def weather_condition(temperature):
... if temperature > 7:
... return "Warm"
... else:
... return "Cold"
...
>>> input("What temperature: ")
What temperature:
teachers:
teacher's screen
And last but not least is the Run script (with or without debug).
debug run
Which opens a completely new Python 'debug' terminal. Here the script runs normally (it seems) and looks more like the teacher's version although his screen doesn't show 'debug' or the small toolbar
small toolbar
anywhere in his visual code.
A. So what is the difference between each of the choices?
B. Which of the 3 should I be using?
C. Why does the first option give an error even though the script is written correctly?
The three options you mention are all specific to VSCode, but you're right that they are intended to give you different ways to run a script.
To answer your questions:
A. So what is the difference between each of the choices?
The first option attempts to start Python in your terminal in VSCode, running a command like:
& "C:/Program Files/Python310/python.exe" c:/project/hello.py
The error message you are seeing is because in your terminal, Python was already running and VSCode just copies and pastes the above into the terminal, expecting it to land on a waiting terminal prompt, not on the Python interactive prompt. If you ran exit() first, to close Python and return to the terminal prompt, and then tried again, it would work.
What the command means is to start that version of Python, running your script, in the current working directory of the terminal, in the current environment of the terminal. (in the background, returning control to you, hence the &)
The second option does something similar, but instead of issuing the command above, just puts everything you selected on the clipboard and pastes it into the terminal. If that happens to be running Python on the interactive prompt, and the text selected is actually Python code, your script may work (depending on the code, and what was run before). If it was sitting on the terminal prompt, it won't because Windows, Linux or Mac OS doesn't understand Python without an interpreter.
The third option is very similar to the first, but instead of just dumping the simple run command in the terminal, it instead adds a few more commands, changing drive and directory and then trying to start the script. It still tries to use the active terminal for it though and it will fail (just as the first option) if Python happened to be running there already.
So, the 1st and 3rd are very similar, but completely different from the 2nd, which is trying to paste Python code instead of terminal commands.
B. Which of the 3 should I be using?
Depends on what you need. If you have a few lines of code you just want to see the effect of, you can use the 2nd method, assuming the lines of code will work in context of what you may have run before.
If you just want to run a script, it depends on where it needs to be run. VSCode gives you some more options to set up your environment for the script to run successfully, but it doesn't give you as much control as something like PyCharm (then again, it's also a lot smaller and quicker to start up than PyCharm and has fewer confusing complicated controls - it's a matter of taste and need).
C. Why does the first option give an error even though the script is written correctly?
As indicated above, it only generates that error when the terminal has an interactive Python session running (you can tell from the >>> prompt). The third one would give you a similar error if you tried it in that setting.
Similarly, the second option will cause problems if you don't have an interactive session started (i.e. running some python.exe).
Is there a way to run Python in Vscode terminal without command?
current result
want result
I've also tried changing the run console from terminal to debug console in Launch.json, but it's not a good way because it's not set globally and don't get key input.
Is there a good way?
And apart from this question, is there any way to get the finished time print like when running Python on a sublime?
I think it's too inefficient to take a final time for each python code.
Right click "Run main.py"
I would like that iPython run automatically when I launch VSC instead of typing ipython and press enter in the terminal. The answer here How to set ipython/jupyter as the default python terminal for vscode? doesn't work as it is for windows but it shouldn't be really different. Also, is there something similar to the 'Execute' button in Spyder instead of typing %run filename ? Thanks !
I presume you mean you want to run the "Python Interactive Window" and not just an iPython console on startup
There is currently no way to run it on startup. At least no way without writing another extension that would run a command when opening a workspace. It would be simple for us to add one though. Probably a workspace setting. Can you log an issue here:
https://github.com/Microsoft/vscode-python/issues/new
For you second question, 'Execute' in spyder, we have 'Run Current File in Python Interactive Window'. This works on any python file. You can get to it through the context menu on a file or through the command palette.
Sadly the nice workflow of spyder is not provided by any official extension at the moment (as far as I know).
But you can implement the basics easily on your own by writing an extension. Even with no experience in TypeScript you can quickly build an extension which starts an IPython console as soon as you open a python file. I also managed to execute a startup script which implements the runfile method. VS Code also allows keybindings for your functions, so that you can almost work like you can with spyder.
Spyder modified the IPython terminal quite a bit though, so it won't feel exactly the same. But after all, everything there is open source so you could implement it yourself, which is what I'm trying to do in my free time.
I would like to know if there is way to figure out (from the IPython console) the .py script that was used to run/execute the python commands interactively and thus got printed into the Ipython console.
For eg.
From the below screenshot, looking at the 3+3 in the Ipython console, I can see that it came in when command from untitled2.py was executed.
However when the scripts get long, and IPython output gets long and you are often shifting scripts on the left side, it can be hard to keep track.
So i was wondering if there is a way i can quickly execute some command or view some setting on Ipython console that can tell me that the above line came from untitled.py.
(Spyder maintainer here) There's no way to know from which Editor you're executing some portion of code, sorry.
However, you could use dedicated consoles (under Preferences > Run > Execute in a dedicated console) to have one console per file you execute, as long as you use F5 to run each one of them.
You could edit each .py script, so the first thing it does is to print its name and functionality.
untitled2.py:
print('untitled2.py')
...
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.