VivekStealsYourCode
VivekStealsYourCode

Reputation: 35

How to make PyCharm Python console work with code?

I am new to PyCharm (coming from IDLE) and still trying to understand how it works. I'm running PyCharm Professional 2019.3.1 on MacOS Mojave.

What I'm asking is that when I run a code in PyCharm, the variables and data aren't stored in the Python console - it remains completely blank and I have to separately write in the console.

For instance, in IDLE:

When I write x = 2 in my program and execute it, I can browse and manipulate the value of x in IDLE's console (by entering > x = 3, > x = 0 etc.), but when I do the same in PyCharm's console it says that x is undefined.

Upvotes: 2

Views: 327

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19430

You are probably simply running the code by using the green arrow or any equivalent way of doing so. The problem is that this runs the script as a separate process and once it finishes, nothing remains from its environment.


If you want to run like in IDLE, where you execute the script and then can access and modify the environment (variables and functions defined) - you want to execute in console. You have a few ways to do that:

  1. Execute Selection in Console - This will execute any highlighted code in the console:

    An image of the Pycharm window, Showing the right-click context menu on an highlighted line of code. The option "Execute selection in console" is highlighted Note that if no code is highlighted, this option will become Execute Line in Console.

  2. One option below that is the Run File in Console. This will, obviously, run the whole script in the console:

    An image of the Pycharm window, Showing the right-click context menu this time without anything highlighted. Now, the option "Execute file in console" is highlighted

    Notice how now you have all the variables defined in the script available in the variables view on the right side.

  3. The last way is to enable this in the Run configurations:

    • Open the Edit Configurations...:

      An image of the Pycharm window, highlighting the option "Edit configurations" that is shown after clicking the drop-down menu next to the run symbol at the top-right corner

    • Then, under Execution, mark the Run with Python console option:

      An image showing the "Edit configurations" window, with the "Run with Python console" option highlighted

    • Now you can run the file regularly, by selecting Run File or using the green triangle.

Note: using method (2) will automatically enable the configuration described in method (3). So basically after running the file once in the console (as described in method (2)), you can go back to running the file regularly and all future runs will be in the console as well (until you un-check the box in the run configuration).

Upvotes: 5

Related Questions