How to make PyCharm Python console work with code?

断了今生、忘了曾经 提交于 2020-05-09 08:21:49

问题


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.


回答1:


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 modify the environment, you want to execute in console. You have a few ways:

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

    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:

    Note how now in the right side, you have the variables defined in the script.

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

    • Open the Edit Configurations...:

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

    • 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 one time in the console (as described in method 2)), you can go back to running the file regularly and these runs will be in the console too (until you un-check the box in the run configuration).



来源:https://stackoverflow.com/questions/60017510/how-to-make-pycharm-python-console-work-with-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!