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.
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).
I've been running some simple python scripts in Pycharm as I develop an app. The below described problem happens with every app within this project, while in other projects I'm not seeing this.
When I run the script, even if it's just a simple
print('Hello World.')
I do not get an exit code. It looks as if I am running the program from the Python Console, but I'm running it by right clicking on the script and choosing run.
I can rerun the script without issue, a new tab just opens in the python console window with an incremental (n) next to the filename.
What I end up doing is clicking on the red stop button which is when I do finally get the exit code. I then close the tab and move on.
In your "Run/Debug Configurations" choose "Emulate terminal ..."
Select emulate terminal in debug configs
I have a little python script that takes a single filename as a command line argument and writes a converted file. Not rocket science, it's 10s of lines long.
I can run that on windows from a cmd prompt simply by typing the name of the script. So for example:
C:\> CD \wheremyscriptis
C:\wheremyscriptis> myscript.py
and it runs fine. Without any arguments it spits out a little Usage message. Quite conventional.
Now we're using Powershell more and more and the first thing I notice in powershell is it won't run at all without an explicit directory, so in the above example I'd need to type .\myscript.py.
That's odd but you could get used to it, not a crisis.
But what happens now is the script runs in another window, which flashes up and disappears before youc an read the usage message.
Given the behavior is inconsistent across these contexts, what can we do inside the script to make the powershell context more usable. Is there a way to detect if we're running in some window that powershell threw up (which is itself weird) and then if so, pause before exiting to give a user a chance to read the usage message before the window disappears?
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.
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.