question
Create a new project in VSCode and use VSCode to run the Python code. You will find the following options: If you
directly click on the triangle, the first item will be executed by default Run Code
.
But if the Python code needs to depend on a specified virtual environment and you click Run Code directly to run it, you will find that the output of the code is in the Output box of the console instead of the Terminal box . At this time, an environment problem will be reported:
take a look , I have configured my own designated virtual environment through Select Python Interpreter in Settings:
If I click on it at this time Run Python File
, there is no problem running, using the myocr virtual environment I set up myself: Here
comes the question: Why is it obvious? I have configured the virtual environment, I click to Run Code
run, and it will run with the default Python interpreter for me?
Run Code
How can I use my own virtual environment to run directly ?
solve
Use the following two steps to set Run Code
the default Python interpreter used:
ctrl
+shift
+p
Open the VSCode window, entersettings
, select the first onePreferences:Open Workspace Settings
:
- Search in the search box
Python Inter
, find the WorkSpace option of the search results, select Python, then enter the Python interpreter path corresponding to the virtual environment of your choice in the Default Interpreter Path, and then check the radio button.
The problem is that you need to set the default python interpreter path. Because when VSCode runs Python code, it actually automatically enters python instructions on the console, and the python instructions need to specify the default interpreter path. If you do not configure it, it will use the Python you installed by default instead of customizing it yourself. Python inside a virtual environment.
reference
Regarding the relationship between VSCode's Run Code and Run Python File, there are many similar answers on StackOverFlow. I feel that it is very helpful to further understand this issue. I strongly recommend that you take a look. Other similar problems can also be solved.
Run Code vs Run Python File in Terminal for VSCODE
How to execute Python code from within Visual Studio Code