问题
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:
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.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.
The last way is to enable this in the Run configurations:
Open the
Edit Configurations...:Then, under
Execution, mark theRun with Python consoleoption:Now you can run the file regularly, by selecting
Run Fileor 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