ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Python入门手册 [toc] 开始创建一个最简单的Python应用程序"Hello world"。 > **Note**: 该手册应用Python 3; 如果用的是Python 2, 需要改写相应的代码; ## 准备工作 要成功完成这个手册的内容,须做如下准备: 1. 下载安装VS CODE,在linux终端输入code启动,code .在当前目录下启动VS Code 1. 安装[Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python). 1. 安装Python3 (该手册例程基于Python3). Options include: - linux已内置Python,可在终端运行Python或python3查看版本 - An installation through [Homebrew](https://brew.sh/) on macOS using `brew install python3` (the system install of Python on macOS is not supported). - python下载1 [python.org](https://www.python.org/downloads/). - python下载2 [Anaconda](https://www.anaconda.com/download/) (用于科学数据). 1. (Windows) 确认环境变量PATH包含了Python解释器路径,可以在命令行终端运行path查看,如果没有包含,需修改环境变量PATH,添加Python解释器的路径; ## 创建文件夹和源文件 新建文件夹"hello", 切换至该路径,打开VS Code (`code`) in that folder (`.`): ``` mkdir hello cd hello code . ``` 菜单,文件 -> 新建文件hello.py,用`.py` 作为文件扩展名, VS Code将自动将其识别为Python文件。下一步在该文件输入如下内容: ```python msg = "Hello World" print(msg) ``` ## 选择一个Python解释器 Python is an interpreted language, and in order to run Python code you must tell VS Code which interpreter to use. From within VS Code, select a Python 3 interpreter using the **Python: Select Interpreter** command on the **Command Palette** (`kb(workbench.action.showCommands)`), or by using the **Select Python Environment** option on the Status Bar if available (it may already show a selected interpreter, too): ![No interpreter selected](images/environments/no-interpreter-selected-statusbar.png) The command presents a list of available interpreters that VS Code can find automatically. If you don't see the desired interpreter, see [Configuring Python environments](/docs/python/environments.md). Selecting an interpreter sets the `python.pythonPath` value in your workspace settings to the path of the interpreter. To see the setting, select **File** > **Preferences** > **Settings**, then select the **Workspace Settings** tab. > **Note**: If you select an interpreter without a workspace folder open, VS Code sets `python.pythonPath` in your user settings instead, which sets the default interpreter for VS Code in general. ## Run Hello World It's simple to run `hello.py` with Python. Right-click in the editor and select **Run Python File in Terminal** (which saves the file automatically): ![Run Python File in Terminal command in the Python editor](images/tutorial/run-python-file-in-terminal.png) The command opens a terminal panel in which your Python interpreter is automatically activated, then runs `python3 hello.py` (Mac/Linux) or `python hello.py`: ![Program output in a Python terminal](images/tutorial/output-in-terminal.png) There are two other ways you can run Python within VS Code: - Select one or more lines, then press `kbstyle(Ctrl+Enter)` or right-click and select **Run Selection/Line in Python Terminal**. This command is very convenient for testing just a part of a file. - Use the **Python: Start REPL** command to opens a REPL terminal for the currently selected Python interpreter. In the REPL you can then enter and run lines of code one at a time. ## 配置和运行debugger 开始调试Hello World程序: 1. 设置在文件`hello.py`之 `print`设置断点,在相应行左侧单击出现红点设置断点; 1. 点击[调试图标]()打开调试窗口; 1. 在调试工具栏选择设置图标(或在菜单栏,Debug -> Open configurations) 1. 打开有效调试器的菜单,显示Python和Python Experimental,选择Python,**Python extersion** 将新建一个文件×launch.json*,该文件包含一系列配置项(在配置下拉菜单中显示)。这些配置项在*Debugging*有详细的解释,这里选择"Python:Current File",该配置项用于选择了Python解释器的当前编辑文件。 **注意:** VS Code用JSON文件保存各种配置信息,*launch.json*是一个标准文件名用于保存调试配置项。 1. 为了在程序调试时程序自动停止于第一行,在*launch.json* -> 配置项*Python:Current File*,添加键值"stopOnEntry": true,如下 ```json { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "stopOnEntry": true }, ``` 保存 `launch.json`, 切换至编辑器文件`hello.py` ,点击Debug工具栏的绿色箭头或按F5键运行 调试器。因为`stopOnEntry`设置为true, 调试器停止于`hello.py` 的第一行,该行高亮黄色,行左侧显示黄色箭头,如果你在此查看**Local** 变量, you see that only automatic dunder variables are defined: 在窗口顶部会出现一个调试工具栏,用于运行、单步、重启和停止程序,状态条改变颜色指示调试模式, **Python Debug Console**会出现在右下的窗口,显示执行的命令和输出。 选择调试工具栏的绿色按钮继续运行程序,调试器停止于断点处,断点处定义的变量 `msg` 将会出现在 **Local**窗口, 可以在右下侧窗口 **Debug Console**操作该变量 (在VS Code右下侧选择 "Debug Console" 或select it from the **...** menu if you don't see it): 选择绿色箭头继续运行,在**Python Debug Console**显示"Hello World" 。至此程序运行结束,自动退出调试模式。 调试时记住之前的调试项设置`stopOnEntry` ,根据需要设置。 ### Troubleshooting If for some reason VS Code doesn't generate `launch.json` for you, create a file by that name within the folder named `.vscode` folder (creating it if you need to), then paste the following contents into `launch.json`: ```json { "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}" } ] } ``` If you see the error below, it means that you attempted to start to debugger when `launch.json` is selected in the editor rather than `hello.py`: ```bash // Use IntelliSense to learn about possible attributes. ^ SyntaxError: invalid syntax ``` Select `hello.py` and try again. Alternately, create a debug configuration specifically for the `hello.py` file by adding the following lines in `launch.json` within the `configuration` array. Then select this configuration in the debugger drop-down and start the debugger again. ```json { "name": "Python: hello.py", "type": "python", "request": "launch", "program": "hello.py" }, ``` ## Install and use packages Let's now run an example that's a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from [PyPi](https://pypi.org/). For this example you use the matplotlib and numpy packages to create a graphical plot as commonly done with data science. Return to **Explorer**, create a new file called `standardplot.py`, and paste in the following source code: ```python import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np x = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the range plt.plot(x, np.sin(x)) # Plot the sine of each x point plt.show() # Display the plot ``` Try running the file in the debugger as described in the last section, without any breakpoints. The message "ModuleNotFoundError: No module named 'matplotlib'" indicates that matplotlib and numpy are not installed in the current interpreter's environment, which is expected (unless you're using an Anaconda installation). To install those packages, switch to the **Python Debug Console** that is already be open. (The Python Debug Console already has the selected interpreter's environment activated. You can also use **Python: Create Terminal** command from the Command Palette.) Enter `pip3 install matplotlib` (macOS/Linux) or `pip install matplotlib` (Windows) to install the matplotlib package (and its dependencies, such as numpy) into that environment. > **Note**: On Linux, you may need to install **tkinter** by running `sudo apt-get install python3-tk`. Also note that if you don't want to install matplotlib and its dependencies globally then use a [virtual environment](https://docs.python.org/3/tutorial/venv.html). Rerun the program now and after a few moments a plot window appears with the output: ![matplotlib output](images/tutorial/plot-output.png) ## Next steps You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see [Environments](/docs/python/environments.md). There is then much more to explore with Python in Visual Studio Code: - [Python environments](/docs/python/environments.md) - Control which Python interpreter is used for editing and debugging. - [Editing code](/docs/python/editing.md) - Learn about autocomplete, IntelliSense, formatting, and refactoring for Python. - [Linting](/docs/python/linting.md) - Enable, configure, and apply a variety of Python linters. - [Debugging](/docs/python/debugging.md) - Learn to debug Python both locally and remotely. - [Unit testing](/docs/python/unit-testing.md) - Configure unit test environments and discover, run, and debug tests. - [Settings reference](/docs/python/settings-reference.md) - Explore the full range of Python-related settings in VS Code.