Difference 'run python file' & 'run lines in terminal' in Microsoft Visual Code - python

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).

Related

PyCharm: Make 'Execute code in console' stop asking me which console

I have configured PyCharm (or, to be more precise, the selected interpreter) to leave the python console open when a program execution has finished. I find it very comfortable to debug and watch things like in RStudio: Marking them in the source window and hitting Control+Enter (or 'any control like button'+Enter). So after discovering the 'Execute Selection in Console' Command I was able to run stuff interactively in the console the script was ran in. However, there are two issues with that:
1) whenever I do this for the first time, PyCharm asks me in which console I want to execute the code. Then of course I always select 'the console in which the script was run'.
2) Even though I select the console the script ran in, the marked code is always executed in a new python shell (so it forgets about all the pandas settings for example, i.e. it only prints two columns or so)
Can one somehow make it run the marked code always in the console the script runs in?
See the following screenshots:
1) run the script
2) change some of the code (i.e. c becomes aa+2*b instead of a+b), mark it and let it run in the console:
3) PyCharm asks me about 'which console to run the marked code in'???
Oopsie, I found the problem. In the run configuration I did put an argument to the python interpreter (namely '-i' which causes the interpreter to leave the session open even though the script has terminated exactly as I wanted it) but the solution was to let PyCharm do that for you by selecting the 'Run with python console' option:
Now every time I run the script it is run in the same console and I can execute code interactively and PyCharm does not ask me anymore in which console I want it to run.

Visual studio code interactive python console

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()\""]

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.

A python 3.5 script not printing results in windows command shell or powershell, only in the interpreter

I'm trying out some data science tutorials with python and can't get print to, well, print! when I run a .py in windows command shell or powershell. Print does work when I use the interpreter, but I have to type it in line by line (I'm not seeing how to run a .py as a file in the interpreter). I'm attaching snips of the file, and a snip of me running in the interpreter. I tried to attach snips of what happens when I run in command shell and powershell, but apparently I need at least 10 reputation points before I can post more than 2 links. Admittedly, those snips weren't interesting; there is no error and nothing printed. It just runs and returns to the prompt.
Also, as a test, I saved a .py file that simply does print ("Hello") and it does print correctly in windows command prompt and powershell.
Thanks in advance for any help!
Casie
PY script
Snip From Python Shell
Is that image from the IDLE console? To run the script you are editing, use menu Run > Run Module, or F5. Every python GUIs has an equivalent feature.
To run an arbitrary script from inside the commandline interpreter, say mywork.py: As long as it's in the working directory that you were in when you started the interpreter, you run it (once) by typing import mywork. (As you can see, its name must be a python identifier.)
Edit: You'd get to the bottom of this a lot quicker if you'd put print("Hello, world") in a script by itself and run it. From over here it looks like it would print just fine, proving there's nothing wrong with your python interpreter.
Your script has a bug, though: As soon as you enter the function random_kid(), you leave it again since you return a value on the first line. All those print statements are never executed. Why you think it works differently with %run I can't say, but for sure this function cannot print any output.

Running a simple script from desktop [duplicate]

This question already has answers here:
How do I run a Python program in the Command Prompt in Windows 7?
(24 answers)
Closed 7 years ago.
So I'm an extreme beginner to programming, just starting the Python class on Coursera. Using Python 2.7.10
Anyway, I made a simple print statement script in Notepad++
print "Hello World"
and saved as a python file on my desktop
newprog.py
However when I try to run it a cmd window appears and disappears and I'm not quite sure whats wrong.
The other question that this was linked as a duplicate to is about accessing python through the command prompt, which I don't have a problem with. From answers given it is now apparent to me that my dilemma was due to an erroneous belief that the interpreter would remain open after running whatever script I wrote.
Sounds like your program simply opened, ran and exited. So nothing was wrong, it just all happened a bit quick for you to see it.
You should run it from a command prompt or get an IDE like Pycharm, which will allow you to both write and run your script in one program.
To run from command prompt, use either Windows Key + R and type 'cmd' or click start and type 'cmd' into search box. Then you can drag your script to the command prompt window and press Enter to run it.
If you wanted to run it by double click, you'd need something to stop it from finishing until you'd read the message. To achieve this you can use the raw_input function, which waits for user input.
So your script would then look like
print "Hello World"
raw_input("Press Enter to exit")
Then you could double click and press enter when you are ready to exit.
Go to the command prompt window
python
then type in
execfile('path to newfile.py here')
Your file will now be executed
I'm running python 3.4.3. But it should be the same, I hope.
Go go "..\PythonXX\Lib\idlelib" and look for idle.pyw NOT idle.py and using the you're able to execute simple one line commands like the one you have up there.
From that you can also create a new file and do more complicated stuff.
If you create a shortcut to your desktop, you'll be able to access it easier.
Let me know if it helps, or at least correct path.
Your script is probably working and then finishing, the result is shown but not for long. I recommend opening the console and running your script from there, or you could use a simple batch file to run python scripts and then wait for a key press.
To open the console you can use the Windows key along the R key, Win-R (to run a new process) and write cmd, or you look for cmd in your Window's start menu.
With the console opened, you must locate the path where your script is, you can use the cd (Change Directory) to get there, for example:
cd C:\Users\your_name\Desktop
and then write:
python newprog.py
to run your script.
Another option is to use this simple batch file (save it as python34.bat or similar, but the extension must be .bat, put it wherever you like):
#ECHO OFF
C:\Python34\python.exe %*
pause
#ECHO ON
And then use that to run your scripts by right clicking a python script file, open with (run with) and use this batch script as default (if you want). Also, if you have another version of Python, or is installed elsewhere, you must change the "C:\Python34\" part.
This is a computer we're talking about here. It might take you triple the time it takes a computer to multiple two numbers for example. With this notion in mind, the computer quickly prints then exits.
raw_input() # at the end of script wait for user to supply input, delaying script exit

Categories

Resources