foreword
Before the article starts, let’s briefly list some of the software/tools that will be used in this article:
-
Python 3 [2]
-
VS Code (version: 1.79.1)
-
VS Code Python extension(Microsoft Python)[3]
Install the Python plugin
To use Python in VS Code, you need to use the Microsoft Python plugin. The plugin leverages VS Code to provide the following features:
- Autocompletion and IntelliSense
- Instrumentation, Debugging and Unit Testing
- Easily switch between Python environments (including virtual environments and conda environments)
Installing plug-ins in VS Code is very simple, just open VS Code, select " Extensions ", enter "Python" in the search bar of " Extensions: Store ", select the corresponding plug-ins, and click "Install":
[----Related technical discussions, learning materials at the end of the article! ----】
After installing the plugin, you usually need to restart VS Code to enable the installed plugin:
After restarting VS Code, open the command panel (⇧⌘P), type " Python ", and you can see some drop-down options appear in the command panel, indicating that the plugin is installed successfully:
Python plugin
General flow using Python
Step 1: Start VS Code in the workspace folder
By launching VS Code in a folder, that folder becomes the "workspace".
Using Command Prompt or Terminal, create an empty folder named , navigate to it, and open VS Code ( ) inside hello
that folder ( ) by entering the following command :.
code
mkdir hello
cd hello
code .
Notes: Before using
code
the command, please make sure that the executable path of VS Code has been added to the environment variable!
Step 2: Create a virtual environment
Best practice for Python developers is to use project-specific virtual environment
. Once this environment is activated, any packages installed are isolated from other environments (including the global interpreter environment), reducing many of the complications that can arise from package version conflicts[4]。
Non-global environments can be created in VS Code using Venv or Conda and Python: Create Environments.
Open the Command Palette ( ⇧⌘P
), start typing the Python: Create Environment command to search for it, and select it. This command displays a list of environment types, Venv or Conda.
The following will take Conda as an example to show the process of creating a virtual environment. The process of Venv and Conda is basically the same:
For Show a list of environment types, Venv or Conda, choose Conda
Then the command will display a list of interpreters available for the project, select the required interpreter
After selecting an interpreter, a notification will be displayed showing the progress of the environment creation
and the environment folder ( /.conda
) will appear in the workspace
Step 3: Create Python source files
From the File Explorer toolbar, choose hello
the New File button on a folder:
Name the file hello.py
and VS Code will automatically open it in the editor:
By using .py
the file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents using the Python extension and the chosen interpreter.
Notes: The File Explorer toolbar also allows creating folders in the workspace to better organize code. Folders can be quickly created using the New Folder button.
Here is a simple example of a demo, now there is a code file in the workspace, hello.py
enter the following source code in :
msg = "Roll a dice"
print(msg)
print
Notice how IntelliSense displays the Auto-completion option when you start typing
IntelliSense and AutoCompletion works with:
- Standard Python modules
- Additional packages installed into the environment of the selected Python interpreter
- methods available on the object type
For example, because msg
the variable contains a string, IntelliSense provides the string method msg.
when you type:
Finally, save the file ( ⌘S
). At this point, you're ready to run your first Python file in VS Code.
Step 4: Run hello.py
Click the Run Python File in Terminal button in the upper right corner of the editor .
This button opens a terminal panel where the Python interpreter is automatically activated, then run python3 hello.py
(macOS/Linux) or python hello.py
(Windows):
There are three other ways to run Python code in VS Code:
- Right-click anywhere in the editor window and select Run > Python File in Terminal (this automatically saves the file)
\2. Select one or more lines and press Shift+Enter
or right-click and select Run Selection/Line in Python Terminal . This command is handy for testing only part of a file
\3. From the command palette ( ⇧⌘P
), select the Python: Start REPL command to open the REPL terminal for the currently selected Python interpreter. In the REPL, you can type and run code one line at a time
Step 5: Configure and run the debugger
Let's try to debug our Hello World program.
First, set a breakpoint on line 2 of by placing the cursor print
on the call and pressing . Alternatively, click the gutter next to the line number on the left side of the editor. When a breakpoint is set, a red circle appears in the gutter.F9
hello.py
Next, to initialize the debugger, press F5
. Since this is the first time this file is being debugged, the configuration menu will open from the command palette, allowing selection of the desired debug configuration type for the opened file.
Notes: All of VS Code's various configurations use JSON files, and launch.json is the standard name for the file containing the debug configuration.
Select Python File , which runs the configuration for the current file displayed in the editor using the currently selected Python interpreter.
Start the debugger by clicking the down arrow next to the Run button on the editor and selecting Debug Python File in Terminal.
The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Locals window at this point, you will see the now defined msg variable appear in the Locals pane.
A debug toolbar appears at the top with the following commands from left to right: Continue ( F5
), Step Over ( F10
), Step Into ( F11
), Exit ( ) ⇧F11
, Restart ( ⇧⌘F5
), and Stop ( ⇧F5
).
The status bar also changes color (orange in many themes) to indicate that you are in debug mode. The Python Debug Console also automatically appears in the lower right panel to show the command being run as well as program output. To continue running the program, choose F5
the Continue command on the Debug toolbar ( ). The debugger runs the program to the end.
Tips: You can also view debugging information by hovering the mouse over the code, for example: variables
msg
, hovering the mouse over the variable will display the string in the box above the variableRoll a dice!
You can also use variables in the debug console (if you don't see it, select the debug console in the bottom right area of VS Code , or select it from the ... menu) then try entering the following line at the > prompt at the bottom of the console :
msg
msg.capitalize()
msg.split()
Select (or press) the blue Continue button on the toolbar again F5
to run the program to completion. If you switch back to the Python debug console, Roll a dice!
it will appear in the Python debug console, and VS Code will exit debug mode once the program completes.
Step 6: Install and use the package
In Python, a package is a way to acquire (usually from) any number of useful code libraries PyPI
that provide additional functionality to a program. For example: use numpy
the package to generate random numbers.
Go back to the Explorer view (the top icon on the left, showing the file), open it hello.py
, then paste the following source code, and run to debug the file:
import numpy as np
msg = "Roll a dice"
print(msg)
print(np.random.randint(1,9))
You should see the message " ModuleNotFoundError: No module named 'numpy' ". This message indicates that a required package is not available in the current interpreter.
To install the numpy package, stop the debugger and run a terminal using the command palette: create a new terminal (⌃⇧ ),并在打开的终端中通过
conda` command to install the appropriate package:
conda install numpy
After the installation is complete, run the program again and find that the random number is successfully output!
Python debugging
By modifying the debugging configuration file, some behaviors in the debugging process can be personalized [ 5] !
Initial configuration
Configuration files often directly determine the behavior of VS Code during a debugging session [ 6] .
Configurations for debugging launch.json
are defined in files, usually stored in the workspace .vscode
folder.
Notes: To change the debug configuration, the code must be stored in a folder!
To initialize a debug configuration, first select the Run and Debug (⇧⌘D) view in the sidebar:
Run icon
If no configuration is currently defined, you will see a button to run and debug and a launch.json
link to create a configuration ( ) file:
To configure a build launch.json
file with Python, the following steps are required:
- Select the link to create a launch.json file (as shown above), or open the command panel (
⇧⌘P
), type "Debug: Add Configuration", select and press Enter
- The configuration menu will open from the command palette, allowing to select the desired debug configuration type for the opened file. Now, in the "Select a debug configuration" menu that appears, select "Python File"
Notes: In the absence of a configuration, starting a debugging session through the debug panel, F5
or Run > Start Debugging will also display the debug configuration menu, but will not create launch.json
a file (that is, in the previous section, "Step 5: Configure and run the debugger " does not create the file as shown launch.json
)
- The Python extension then creates and opens a
launch.json
file containing a predefined configuration based on the previous selection (ie: "Python File"). You can modify the configuration (such as adding parameters), or add custom configurations
additional configuration
By default, VS Code only shows the most common configurations provided by the Python extension. Additional configurations to be included in can be selected using the Add Configuration command and launch.json
editor shown in the list. launch.json
When using this command, VS Code will prompt and provide a list of all available configurations (be sure to select the Python option):
Selecting "Attach using Process ID" produces the following:
During debugging, the status bar shows the current configuration and the current debugging interpreter. Selecting a configuration will bring up a list from which you can choose a different configuration:
By default, the debugger uses the same interpreter selected for the workspace, as other features of VS Code's Python extension do. launch.json
To debug exclusively with a different interpreter, set the value in for the applicable debugger configuration python
. Alternatively, select the specified interpreter on the status bar to choose a different interpreter.
Set configuration options
When first created launch.json
, there are two standard configurations to run the active file in the editor in the integrated terminal (inside VS Code) or in the external terminal (outside VS Code):
{
"configurations": [
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
},
{
"name": "Python: Current File (External Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "externalTerminal"
}
]
}
launch.json
The following will give some brief descriptions of the configuration items of the more common files.
name
: Provide the name of the debug configuration shown in the VS Code dropdown
type
: Identifies the type of debugger to use
For Python code, leave this setting aspython
request
: Specifies the mode to start debugging
There are two common debugging modes:
launch
:program
start the debugger on the file specified inattach
: Attach the debugger to an already running process, which will be used in remote debugging
program
: Provide the absolute path of the entry module (startup file) of the python program
Value ${file}
is usually used in the default configuration, using the currently active file in the editor.
By specifying a specific startup file, you can always ensure that the program is started with the same entry point, no matter which files are open. For example:
"program": "/Users/Me/Projects/PokemonGo-Bot/pokemongo_bot/event_handlers/__init__.py",
You can also rely on relative paths to the workspace root ( ${workspaceFolder}
)
For example, if the root is /Users/Me/Projects/PokemonGo-Bot
, then the following example could be used:
"program": "${workspaceFolder}/pokemongo_bot/event_handlers/__init__.py",
module
: Provides the ability to specify the name of the module to debug
Similar to the -m parameter when running on the command line.
python
: the full path to the Python interpreter used for debugging
If not specified, this setting defaults to the interpreter chosen for your workspace, which is equivalent to using the value ${command:python.interpreterPath}
.
To use a different interpreter, specify its path in the debug configuration's python properties.
Alternatively, a custom environment variable defined on each platform can be used to include the full path to the Python interpreter to use so that no additional folder paths are required.
If you need to pass arguments to the Python interpreter, you can use pythonArgs
the attribute.
pythonArgs
: pass parameters to the Python interpreter
Use the syntax "pythonArgs": ["", "",...]
to specify arguments to pass to the Python interpreter.
args
: Specifies the parameters to be passed to the Python program
Each element of the parameter string separated by spaces should be enclosed in quotes, for example:
"args": ["--quiet", "--norepeat", "--port", "1593"],
console
: Specifies redirectOutput
how to display program output without modifying the default value of
Specifically, there are three options:
"internalConsole"
: VS Code debugging console. No output is displayed ifredirectOutput
set toFalse
"integratedTerminal"
(default) : VS Code integrated terminal. Output is also shown in the debug console ifredirectOutput
set toTrue
"externalTerminal"
: A separate console window. Output is also shown in the debug console ifredirectOutput
set toTrue
purpose
: Configure the "Run" button
Set purpose
the option to debug-test
, to define that this configuration should be used when debugging tests in VS Code.
However, setting this option to debug-in-terminal
defines that this configuration should only be used when accessing the "Run Python File" button in the upper right corner of the editor (regardless of whether the button offers the "Run Python File" or "Debug Python File" option).
F5
Notes: The purpose option cannot be used to start the debugger via or "Run > Start Debugging".
autoReload
: reload after modification
Allows automatic reloading of the debugger when changes are made to the code after debugger execution hits a breakpoint. To enable this feature, set {"enable": true}
, as shown in the following code:
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"autoReload": {
"enable": true
}
}
Notes: When the debugger performs a reload, code that was running at import time may be executed again. To avoid this, try to use only imports, constants, and definitions in modules, and put all code in functions. Alternatively, you can use
if __name__=="__main__"
the check.
cwd
: Specifies the current working directory of the debugger
This is the base folder for any relative paths used in the code. If omitted, defaults to ${workspaceFolder}
(folder opened in VS Code)
redirectOutput
: redirect output
When set to true
( internalConsole
the default), causes the debugger to print all output from the program to the VS Code debug output window.
If set to false
( the default for integratedTerminal
and externalTerminal
), program output is not shown in the debugger output window.
This option is usually disabled when using "console": "integratedTerminal"
or "console": "externalTerminal"
, since there is no need to duplicate the output in the debug console.
justMyCode
: Only debug user-written code
When omitted or set to true
(the default), only debug user-written code. Setting to false
also enables debugging of standard library functions.
env
: Set optional environment variables other than system environment variables
Sets optional environment variables for the debugger process in addition to the system environment variables that the debugger always inherits. Values for these variables must be entered as strings.
envFile
: optional path to a file containing environment variable definitions
postscript
For VS Code or PyCharm, this kind of tool provides users with nothing more than a three-stage service. If it is described by the front, middle and later stages:
-
In the early stage, in the environment configuration stage, configure the compiler/interpreter, debugger, and debugger configuration files required by the programming language;
-
In the mid-term, functions such as auto-completion, smart prompts, and automatic jumps when editing code;
-
The later stage is in the running and debugging stage. By providing a visual interface, users can debug code more conveniently.
In fact, I feel that the most valuable for this kind of tool, and the key that can best reflect whether this tool is easy to use, is the functions provided in the mid-term, because the functions provided in the early and late stages are not very useful. No, if you have more experience, you can do these tasks by yourself.
Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:
1. Learning routes in all directions of Python
Just started learning python, if you don't even plan the complete learning steps, it is basically impossible to learn python. He sorted out all the directions of Python to form a summary of knowledge points in various fields.(The picture is too big, I can’t put it here, if you don’t have a full version, you can get it for free at the end of the article)
Some hard skills needed to engage in data analysis, such as how to use python, SQL and other tools!
2. Getting started with a full set of learning videos
When we watch videos and learn, we can’t just move our eyes and brain without using our hands. A more scientific learning method is to use them after understanding. At this time, the hands-on project is very suitable.
Three, Python operation example
Learning python is the same as learning mathematics. You can’t just read the book without doing the questions. Looking directly at the steps and answers will make people mistakenly think that you have mastered everything, but you will still be at a loss when you encounter a problem.
Therefore, in the process of learning python, you must remember to write more codes by hand. You only need to read the tutorial once or twice.
4. Python employment project actual combat
We must learn Python to find a high-paying job or a high-paying part-time job. The following are some practical projects that companies can use. After learning these, I believe everyone will be able to find a satisfactory job.
11 Django Framework
16 WeChat public account
18 Common crawler module usage
…
21 Data Analysis
22 Machine Learning
There are other things, such as my own Python introductory graphic tutorials, you can use your mobile phone to learn knowledge when you don’t have a computer, and after learning the theory, you can type the code to practice verification, and there is also the library information of the Chinese version of Python. , MySQL and HTML tags, etc., these are things that can be given to fans.
Data collection
These are not very valuable things, but they are really good for learners who have no resources or the resources are not very good. If you can use it, you can scan the QR code of CSDN official certification below on WeChat [free access]↓↓↓ .
Good article recommendation
Understand the prospect of python: https://blog.csdn.net/SpringJavaMyBatis/article/details/127194835
Learn about python's part-time sideline: https://blog.csdn.net/SpringJavaMyBatis/article/details/127196603