One of the coolest code editors available to programmers, Visual Studio Code, is an open-source, extensible, light-weight editor available on all platforms. It’s these qualities that make Visual Studio Code from Microsoft very popular, and a great platform for Python development.
可供程序员使用的最酷的代码编辑器之一, Visual Studio Code ,是一种可在所有平台上使用的开源,可扩展,轻量级的编辑器。 这些特性使Microsoft的 Visual Studio Code变得非常流行,并且成为Python开发的绝佳平台。
In this article, you’ll learn about Python development in Visual Studio Code, including how to:
在本文中,您将学习Visual Studio Code中的Python开发,包括如何:
We assume you are familiar with Python development and already have some form of Python installed on your system (Python 2.7, Python 3.6/3.7, Anaconda, or others). Screenshots and demos for Ubuntu and Windows are provided. Because Visual Studio Code runs on all major platforms, you may see slightly different UI elements and may need to modify certain commands.
我们假设您熟悉Python开发,并且已经在系统上安装了某种形式的Python(Python 2.7,Python 3.6 / 3.7,Anaconda或其他)。 提供了Ubuntu和Windows的屏幕截图和演示。 由于Visual Studio Code在所有主要平台上运行,因此您可能会看到略有不同的UI元素,并且可能需要修改某些命令。
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
免费奖金: 关于Python精通的5个想法 ,这是针对Python开发人员的免费课程,向您展示了将Python技能提升到新水平所需的路线图和心态。
Installing Visual Studio Code is very accessible on any platform. Full instructions for Windows, Mac, and Linux are available, and the editor is updated monthly with new features and bug fixes. You can find everything at the Visual Studio Code website:
在任何平台上都可以很容易地安装Visual Studio Code。 提供了有关Windows , Mac和Linux的完整说明,并且该编辑器每月更新一次,其中包含新功能和错误修复。 您可以在Visual Studio Code网站上找到所有内容:
In case you were wondering, Visual Studio Code (or VS Code for short) shares almost nothing other than a name with its larger Windows-based namesake, Visual Studio.
如果您想知道,Visual Studio Code(或简称VS Code)几乎没有共享任何东西,除了与其更大的基于Windows的同名Visual Studio共享一个名称外。
Visual Studio Code has built-in support for multiple languages and an extension model with a rich ecosystem of support for others. VS Code is updated monthly, and you can keep up to date at the Microsoft Python blog. Microsoft even makes the VS Code GitHub repo available for anyone to clone and contribute. (Cue the PR flood.)
Visual Studio Code具有对多种语言的内置支持,以及具有丰富的对其他语言的支持的扩展模型。 VS Code每月更新一次,您可以在Microsoft Python博客上保持最新。 微软甚至使任何人都可以克隆和贡献VS Code GitHub存储库 。 (提示PR洪水。)
The VS Code UI is well documented, so I won’t rehash it here:
VS Code用户界面有充分的文档说明,因此在这里我不会对其进行重新哈希处理:
As stated above, VS Code supports development in multiple programming languages through a well-documented extension model. The Python extension enables Python development in Visual Studio Code, with the following features:
如上所述,VS Code通过完善的扩展模型支持多种编程语言的开发。 Python扩展启用了Visual Studio Code中的Python开发,具有以下功能:
Visual Studio Code extensions cover more than just programming language capabilities:
Visual Studio Code扩展不仅涵盖编程语言功能,还包括:
Keymaps allow users already familiar with Atom, Sublime Text, Emacs, Vim, PyCharm, or other environments to feel at home.
Themes customize the UI whether you like coding in the light, dark, or something more colorful.
Language packs provide a localized experience.
键盘映射使已经熟悉Atom, Sublime Text , Emacs , Vim ,PyCharm或其他环境的用户感到宾至如归。
无论您喜欢在浅色,深色或其他更彩色的代码中进行编码, 主题都可以自定义UI。
语言包提供本地化的体验。
Here are some other extensions and settings I find useful:
以下是一些其他有用的扩展程序和设置:
GitLens provides tons of useful Git features directly in your editing window, including blame annotations and repository exploration features.
Auto save is easily turned on by selecting File, Auto Save
from the menu. The default delay time is 1000 milliseconds, which is also configurable.
Settings Sync allows you to synchronize your VS Code settings across different installations using GitHub. If you work on different machines, this helps keep your environment consistent across them.
Docker lets you quickly and easily work with Docker, helping author Dockerfile
and docker-compose.yml
, package and deploy your projects, and even generate the proper Docker files for your project.
GitLens直接在您的编辑窗口中提供了大量有用的Git功能,包括非常规注释和资源库浏览功能。
通过从菜单中选择File, Auto Save
,可以轻松打开File, Auto Save
。 默认延迟时间是1000毫秒,也可以配置 。
Settings Sync允许您使用GitHub在不同的安装之间同步VS Code设置。 如果您在不同的计算机上工作,这有助于使环境在它们之间保持一致。
Docker使您可以快速轻松地使用Docker,帮助编写Dockerfile
和Dockerfile
docker-compose.yml
,打包和部署您的项目,甚至为您的项目生成正确的Docker文件。
Of course, you may discover other useful extensions as you use VS Code. Please share your discoveries and settings in the comments!
当然,在使用VS Code时,您可能会发现其他有用的扩展。 请在评论中分享您的发现和设置!
Discovering and installing new extensions and themes is accessible by clicking on the Extensions icon on the Activity Bar. You can search for extensions using keywords, sort the results numerous ways, and install extensions quickly and easily. For this article, install the Python extension by typing python
in the Extensions item on the Activity Bar, and clicking Install:
通过单击活动栏上的扩展图标,可以发现并安装新的扩展和主题。 您可以使用关键字搜索扩展名,以多种方式对结果进行排序,并快速,轻松地安装扩展名。 对于本文,通过在活动栏上的扩展项中键入python
并单击安装来安装Python扩展:
You can find and install any of the extensions mentioned above in the same manner.
您可以以相同的方式查找和安装上述任何扩展。
One important thing to mention is that Visual Studio Code is highly configurable through user and workspace settings.
值得一提的是,Visual Studio Code可通过用户和工作区设置进行高度配置。
User settings are global across all Visual Studio Code instances, while workspace settings are local to the specific folder or project workspace. Workspace settings give VS Code tons of flexibility, and I call out workspace settings throughout this article. Workspace settings are stored as .json
files in a folder local to the project workspace called .vscode
.
用户设置在所有Visual Studio Code实例中都是全局的,而工作区设置是特定文件夹或项目工作区的本地设置。 工作区设置为VS Code带来了极大的灵活性,在本文中,我都提到了工作区设置。 工作空间设置作为.json
文件存储在项目工作空间本地的名为.vscode
的文件夹中。
Let’s start our exploration of Python development in Visual Studio Code with a new Python program. In VS Code, type Ctrl+N to open a new File. (You can also select File, New from the menu.)
让我们开始使用新的Python程序探索Visual Studio Code中的Python开发。 在VS Code中, 按Ctrl + N打开一个新文件。 (您也可以从菜单中选择“文件”,“新建”。)
Note: The Visual Studio Code UI provides the Command Palette, from which you can search and execute any command without leaving the keyboard. Open the Command Palette using Ctrl+Shift+P, type File: New File
, and hit Enter to open a new file.
注意: Visual Studio Code UI提供了“ 命令面板” ,您可以在不离开键盘的情况下从中搜索和执行任何命令。 使用Ctrl + Shift + P打开命令面板,键入File: New File
,然后按Enter打开一个新文件。
No matter how you get there, you should see a VS Code window that looks similar to the following:
无论如何到达那里,都应该会看到一个类似于以下内容的“ VS代码”窗口:
Once a new file is opened, you can being entering code.
打开新文件后,即可输入代码。
For our test code, let’s quickly code up the Sieve of Eratosthenes (which finds all primes less than a given number). Begin typing the following code in the new tab you just opened:
对于我们的测试代码,让我们快速编写Eratosthenes筛 (发现小于给定数字的所有素数)的代码。 在刚打开的新标签中开始输入以下代码:
sieve sieve = = [[ TrueTrue ] ] * * 101
101
for for i i in in rangerange (( 22 , , 100100 ):
):
You should see something similar to this:
您应该看到类似以下内容:
Wait, what’s going on? Why isn’t Visual Studio Code doing any keyword highlighting, any auto-formatting, or anything really helpful? What gives?
等等,这是怎么回事? 为什么Visual Studio Code不执行任何关键字突出显示,任何自动格式设置或任何真正有用的操作? 是什么赋予了?
The answer is that, right now, VS Code doesn’t know what kind of file it’s dealing with. The buffer is called Untitled-1
, and if you look in the lower right corner of the window, you’ll see the words Plain Text.
答案是,现在,VS Code不知道它正在处理哪种文件。 该缓冲区称为Untitled-1
,如果您在窗口的右下角看,会看到“纯文本”字样。
To activate the Python extension, save the file (by selecting File, Save from the menu, File:Save File from the Command Palette, or just using Ctrl+S) as sieve.py
. VS Code will see the .py
extension and correctly interpret the file as Python code. Now your window should look like this:
要激活Python扩展,请将文件保存为sieve.py
(通过选择File,从菜单中选择Save,从Command Palette中选择File:Save File,或仅使用Ctrl + S )。 VS Code将显示.py
扩展名,并将文件正确解释为Python代码。 现在,您的窗口应如下所示:
That’s much better! VS Code automatically reformats the file as Python, which you can verify by inspecting the language mode in the lower left corner.
那好多了! VS Code会自动将文件重新格式化为Python,您可以通过检查左下角的语言模式来进行验证。
If you have multiple Python installations (like Python 2.7, Python 3.x, or Anaconda), you can change which Python interpreter VS Code uses by clicking the language mode indicator, or selecting Python: Select Interpreter from the Command Palette. VS Code supports formatting using pep8
by default, but you can select black
or yapf
if you wish.
如果您安装了多个Python(例如Python 2.7,Python 3.x或Anaconda),则可以通过单击语言模式指示符或选择Python来更改VS Code使用的Python解释器:从“命令面板”中选择“解释器”。 VS Code默认支持使用pep8
进行格式化 ,但您可以根据需要选择black
或yapf
。
Let’s add the rest of the Sieve code now. To see IntelliSense at work, type this code directly rather than cut and paste, and you should see something like this:
现在让我们添加其余的Sieve代码。 要查看IntelliSense的工作原理,请直接键入以下代码,而不是剪切和粘贴,您将看到类似以下内容的内容:
Here’s the full code for a basic Sieve of Eratosthenes:
这是基本的Eratosthenes筛网的完整代码:
As you type this code, VS Code automatically indents the lines under for
and if
statements for you properly, adds closing parentheses, and makes suggestions for you. That’s the power of IntelliSense working for you.
键入此代码时,VS Code会自动for
和if
语句缩进适当的行,添加右括号并为您提供建议。 这就是IntelliSense为您工作的力量。
Now that the code is complete, you can run it. There is no need to leave the editor to do this: Visual Studio Code can run this program directly in the editor. Save the file (using Ctrl+S), then right-click in the editor window and select Run Python File in Terminal:
现在代码已完成,您可以运行它。 无需离开编辑器即可执行此操作:Visual Studio Code可以直接在编辑器中运行此程序。 保存文件(使用Ctrl + S ),然后在编辑器窗口中右键单击并选择“在终端中运行Python文件”:
You should see the Terminal pane appear at the bottom of the window, with your code output showing.
您应该看到终端窗格出现在窗口的底部,并显示您的代码输出。
You may have seen a pop up appear while you were typing, stating that linting was not available. You can quickly install linting support from that pop up, which defaults to PyLint. VS Code also supports other linters. Here’s the complete list at the time of this writing:
键入时,您可能会看到一个弹出窗口,提示无法使用棉绒。 您可以从该弹出窗口中快速安装linting支持,默认为PyLint。 VS Code还支持其他短毛猫。 这是撰写本文时的完整列表:
pylint
flake8
mypy
pydocstyle
pep8
prospector
pyllama
bandit
pylint
flake8
mypy
pydocstyle
pep8
prospector
pyllama
bandit
The Python linting page has complete details on how to setup each linter.
Python棉绒页面包含有关如何设置每个棉绒的完整详细信息。
Note: The choice of linter is a project workspace setting, and not a global user setting.
注意 :linter的选择是项目工作区设置,而不是全局用户设置。
In the Sieve of Eratosthenes example, you created a single Python file. That’s great as an example, but many times, you’ll create larger projects and work on them over a longer period of time. A typical new project work flow might look like this:
在Eratosthenes的Sieve示例中,您创建了一个Python文件。 作为一个很好的例子,但是很多时候,您将创建更大的项目并在更长的时间内进行处理。 典型的新项目工作流程可能如下所示:
code filename.py
code filename.py
创建初始Python代码 Using Visual Studio Code on a Python project (as opposed to a single Python file) opens up tons more functionality that lets VS Code truly shine. Let’s take a look at how it works with a larger project.
在Python项目(与单个Python文件相对)上使用Visual Studio Code可以带来更多功能,使VS Code真正发挥作用。 让我们看一下它如何与更大的项目一起工作。
Late in the previous millennium, when I was a much younger programmer, I wrote a calculator program that parsed equations written in infix notation, using an adaptation of Edsger Dijkstra’s shunting yard algorithm.
在上个千年的晚期,当我还是一个更年轻的程序员时,我编写了一个计算器程序,该程序使用Edsger Dijkstra的调车码算法的改编来解析以后缀符号表示的方程式。
To demonstrate the project-focused features of Visual Studio Code, I began recreating the shunting yard algorithm as an equation evaluation library in Python. To continue following along, feel free to clone the repo locally.
为了演示Visual Studio Code的以项目为中心的功能,我开始在Python中重新创建调车场算法作为方程评估库 。 要继续进行下去,请随时在本地克隆存储库。
Once the folder is created locally, you can open the entire folder in VS Code quickly. My preferred method (as mentioned above) is modified as follows, since I already have the folder and basic files created:
在本地创建文件夹后,您可以在VS Code中快速打开整个文件夹。 我的首选方法(如上所述)如下修改,因为我已经创建了文件夹和基本文件:
cd /path/to/project
code .
cd /path/to/project
code .
VS Code understands, and will use, any virtualenv, pipenv, or conda environments it sees when opened this way. You don’t even need to start the virtual environment first! You can even open a folder from the UI, using File, Open Folder from the menu, Ctrl+K, Ctrl+O from the keyboard, or File:Open Folder from the Command Palette.
VS代码的理解,并会使用,任何的virtualenv , pipenv ,或畅达打开这种方式,当它看到的环境。 您甚至不需要先启动虚拟环境! 您甚至可以从UI中打开文件夹,方法是使用文件,菜单中的打开文件夹, 键盘上的Ctrl + K , Ctrl + O或命令面板中的File:Open文件夹。
For my equation eval library project, here’s what I see:
对于我的方程式评估库项目,这是我看到的内容:
When Visual Studio Code opens the folder, it also opens the files you last had opened. (This is configurable.) You can open, edit, run, and debug any file listed. The Explorer view in the Activity Bar on the left gives you a view of all the files in the folder and shows how many unsaved files exist in the current set of tabs.
当Visual Studio Code打开文件夹时,它还会打开您上次打开的文件。 (这是可配置的。)您可以打开,编辑,运行和调试列出的任何文件。 左侧活动栏中的资源管理器视图为您提供了文件夹中所有文件的视图,并显示了当前选项卡集中存在多少未保存的文件。
VS Code can automatically recognize existing Python tests written in the unittest
framework, or the pytest
or Nose
frameworks if those frameworks are installed in the current environment. I have a unit test written in unittest
for the equation eval library, which you can use for this example.
VS Code可以自动识别用unittest
框架或pytest
或Nose
框架(如果这些框架安装在当前环境中)编写的现有Python测试 。 我在unittest
为方程式eval库编写了一个单元测试 ,您可以在本示例中使用它。
To run your existing unit tests, from any Python file in the project, right-click and select Run Current Unit Test File. You’ll be prompted to specify the test framework, where in the project to search for tests, and the filename pattern your tests utilize.
要运行现有的单元测试,请从项目中的任何Python文件中,右键单击并选择“运行当前单元测试文件”。 系统将提示您指定测试框架,项目中要搜索测试的位置以及测试使用的文件名模式。
All of these are saved as workspace settings in your local .vscode/settings.json
file and can be modified there. For this equation project, you select unittest
, the current folder, and the pattern *_test.py
.
所有这些都作为工作区设置保存在本地.vscode/settings.json
文件中,可以在此处进行修改。 对于此方程式项目,选择unittest
,当前文件夹和模式*_test.py
。
Once the test framework is set up and the tests have been discovered, you can run all your tests by clicking Run Tests on the Status Bar and selecting an option from the Command Palette:
一旦建立了测试框架并找到了测试,就可以通过单击状态栏上的“运行测试”并从“命令面板”中选择一个选项来运行所有测试:
You can even run individual tests by opening the test file in VS Code, clicking Run Tests on the Status Bar, and selecting the Run Unit Test Method… and the specific test to run. This makes it trivial to address individual test failures and re-run only failed tests, which is a huge time-saver! Test results are shown in the Output pane under Python Test Log.
您甚至可以通过在VS Code中打开测试文件,单击状态栏上的“运行测试”,然后选择“运行单元测试方法”以及要运行的特定测试来运行单个测试。 这使得处理单个测试失败并仅重新运行失败的测试变得微不足道,这可以节省大量时间! 测试结果显示在“ Python测试日志”下的“输出”窗格中。
Even though VS Code is a code editor, debugging Python directly within VS Code is possible. VS Code offers many of the features you would expect from a good code debugger, including:
即使VS Code是代码编辑器,也可以直接在VS Code中调试Python 。 VS Code提供了许多优秀的代码调试器所期望的功能,其中包括:
You can see them all as part of the Debug view on the Activity Bar:
您可以在活动栏的“调试”视图中看到它们的全部内容:
The debugger can control Python apps running in the built-in terminal or an external terminal instance. It can attach to an already running Python instances, and can even debug Django and Flask apps.
调试器可以控制在内置终端或外部终端实例中运行的Python应用程序。 它可以附加到已经运行的Python实例,甚至可以调试Django和Flask应用。
Debugging code in a single Python file is as simple as starting the debugger using F5. You use F10 and F11 to step over and into functions respectively, and Shift+F5 to exit the debugger. Breakpoints are set using F9, or using the mouse by clicking in the left margin in the editor window.
在单个Python文件中调试代码就像使用F5启动调试器一样简单。 您可以使用F10和F11分别进入和进入函数,并使用Shift + F5退出调试器。 使用F9或通过在编辑器窗口中的左空白处单击鼠标来设置断点。
Before you start debugging more complicated projects, including Django or Flask applications, you need to setup and then select a debug configuration. Setting up the debug configuration is relatively straightforward. From the Debug view, select the Configuration drop-down, then Add Configuration, and select Python:
在开始调试更复杂的项目(包括Django或Flask应用程序)之前,需要进行设置,然后选择调试配置。 设置调试配置相对简单。 在“调试”视图中,选择“配置”下拉菜单,然后选择“添加配置”,然后选择“ Python”:
Visual Studio Code will create a debug configuration file under the current folder called .vscode/launch.json
, which allows you to setup specific Python configurations as well as settings for debugging specific apps, like Django and Flask.
Visual Studio Code将在当前文件夹.vscode/launch.json
下创建一个调试配置文件,该文件允许您设置特定的Python配置以及用于调试特定应用程序 (如Django和Flask)的设置。
You can even perform remote debugging, and debug Jinja and Django templates. Close the launch.json
file in the editor and select the proper configuration for your application from the Configuration drop-down.
您甚至可以执行远程调试,并调试Jinja和Django模板。 在编辑器中关闭launch.json
文件,然后从“配置”下拉列表中选择适合您的应用程序的配置。
VS Code has built-in support for source control management, and ships with support for Git and GitHub right out of the box. You can install support for other SCM’s in VS Code, and use them side by side. Source control is accessible from the Source Control view:
VS Code内置了对源代码管理的支持,并立即提供对Git和GitHub的支持。 您可以在VS Code中安装对其他SCM的支持,并排使用它们。 可从“源代码管理”视图访问源代码管理:
If your project folder contains a .git
folder, VS Code automatically turns on the full range of Git/GitHub functionality. Here are some of the many tasks you can perform:
如果您的项目文件夹包含.git
文件夹,则VS Code会自动打开所有Git / GitHub功能。 以下是您可以执行的许多任务中的一些:
All of this functionality is available directly from the VS Code UI:
所有这些功能都可以直接从VS Code用户界面获得:
VS Code will also recognize changes made outside the editor and behave appropriately.
VS Code还将识别在编辑器之外进行的更改并表现适当。
Committing your recent changes within VS Code is a fairly straightforward process. Modified files are shown in the Source Control view with an M marker, while new untracked files are marked with a U. Stage your changes by hovering over the file and then clicking the plus sign (+). Add a commit message at the top of the view, and then click the check mark to commit the changes:
在VS Code中提交最近的更改是一个相当简单的过程。 修改后的文件在源代码管理视图中显示为M标记,而未跟踪的新文件则用U标记。将更改悬停在文件上,然后单击加号(+),以进行更改。 在视图顶部添加一个提交消息,然后单击复选标记以提交更改:
You can push local commits to GitHub from within VS Code as well. Select Sync from the Source Control view menu, or click Synchronize Changes on the status bar next to the branch indicator.
您也可以从VS Code中将本地提交推送到GitHub。 从“源代码管理”视图菜单中选择“同步”,或在分支指示器旁边的状态栏上单击“同步更改”。
Visual Studio Code is one of the coolest general purpose editors and a great candidate for Python development. In this article, you learned:
Visual Studio Code是最酷的通用编辑器之一,也是Python开发的理想之选。 在本文中,您了解了:
Visual Studio Code has become my default editor for Python and other tasks, and I hope you give it a chance to become yours as well.
Visual Studio Code已成为我用于Python和其他任务的默认编辑器,希望您也有机会成为您的默认编辑器。
If you have questions or comments, please reach out in the comments below. There is also a lot more information at the Visual Studio Code website than we could cover here.
如果您有任何疑问或意见,请访问以下评论。 在Visual Studio Code网站上,还有很多信息比我们在这里可以涵盖的更多。
The author sends thanks to Dan Taylor from the Visual Studio Code team at Microsoft for his time and invaluable input in this article.
作者感谢Microsoft Visual Studio Code团队的Dan Taylor ,感谢他的宝贵时间和本文中的宝贵意见。
翻译自: https://www.pybloggers.com/2019/02/python-development-in-visual-studio-code/