使用 VS Code 进行 Python 编程
Python VSCode
![](/data/attachment/album/201809/08/083157eicjayyyy1a85q85.jpg)


Visual Studio Code，简称 VS Code，是一个开源的文本编辑器，包含用于构建和调试应用程序的工具。安装启用 Python 扩展后，VS Code 可以配置成理想的 Python 开发工作环境。本文将介绍一些有用的 VS Code 扩展，并配置它们以充分提高 Python 开发效率。


如果你的计算机上还没有安装 VS Code，可以参考文章 [在 Fedora 上使用 VS Code](https://fedoramagazine.org/using-visual-studio-code-fedora/) 来安装。


### 在 VS Code 中安装 Python 扩展


首先，为了更方便地在 VS Code 中进行 Python 开发，需要从 VS Code 扩展商店中安装 Python 扩展。


![](/data/attachment/album/201809/08/083158y9jgv3i2aghav5vz.gif)


Python 扩展安装完成后，就可以开始配置 Python 扩展了。


VS Code 通过两个 JSON 文件管理设置:


* 一个文件用于 VS Code 的全局设置，作用于所有的项目
* 另一个文件用于特殊设置，作用于单独项目


可以用快捷键 `Ctrl+,` （逗号）打开全局设置，也可以通过 **文件 -> 首选项 -> 设置** 来打开。


#### 设置 Python 路径


您可以在全局设置中配置 `python.pythonPath` 使 VS Code 自动为每个项目选择最适合的 Python 解释器。



```
// 将设置放在此处以覆盖默认设置和用户设置。
// Path to Python, you can use a custom version of Python by modifying this setting to include the full path.
{
    "python.pythonPath":"${workspaceRoot}/.venv/bin/python",
}
```

这样，VS Code 将使用虚拟环境目录 `.venv` 下项目根目录中的 Python 解释器。


#### 使用环境变量


默认情况下，VS Code 使用项目根目录下的 `.env` 文件中定义的环境变量。 这对于设置环境变量很有用，如：



```
PYTHONWARNINGS="once"
```

可使程序在运行时显示警告。


可以通过设置 `python.envFile` 来加载其他的默认环境变量文件：



```
// Absolute path to a file containing environment variable definitions.
"python.envFile": "${workspaceFolder}/.env",
```

### 代码分析


Python 扩展还支持不同的代码分析工具（pep8、flake8、pylint）。要启用你喜欢的或者正在进行的项目所使用的分析工具，只需要进行一些简单的配置。


扩展默认情况下使用 pylint 进行代码分析。你可以这样配置以使用 flake8 进行分析：



```
"python.linting.pylintEnabled": false,
"python.linting.flake8Path": "${workspaceRoot}/.venv/bin/flake8",
"python.linting.flake8Enabled": true,
"python.linting.flake8Args": ["--max-line-length=90"],
```

启用代码分析后，分析器会在不符合要求的位置加上波浪线，鼠标置于该位置，将弹窗提示其原因。注意，项目的虚拟环境中需要安装有 flake8，此示例方能有效。


![](/data/attachment/album/201809/08/083159kqn1le2220agsdhy.gif)


### 格式化代码


可以配置 VS Code 使其自动格式化代码。目前支持 autopep8、black 和 yapf。下面的设置将启用 “black” 模式。



```
// Provider for formatting. Possible options include 'autopep8', 'black', and 'yapf'.
"python.formatting.provider": "black",
"python.formatting.blackPath": "${workspaceRoot}/.venv/bin/black"
"python.formatting.blackArgs": ["--line-length=90"],
"editor.formatOnSave": true,
```

如果不需要编辑器在保存时自动格式化代码，可以将 `editor.formatOnSave` 设置为 `false` 并手动使用快捷键 `Ctrl + Shift + I` 格式化当前文档中的代码。 注意，项目的虚拟环境中需要安装有 black，此示例方能有效。


### 运行任务


VS Code 的一个重要特点是它可以运行任务。需要运行的任务保存在项目根目录中的 JSON 文件中。


#### 运行 flask 开发服务


这个例子将创建一个任务来运行 Flask 开发服务器。 使用一个可以运行外部命令的基本模板来创建新的工程：


![](/data/attachment/album/201809/08/083159mx9x9asgblrpaxb7.gif)


编辑如下所示的 `tasks.json` 文件，创建新任务来运行 Flask 开发服务：



```
{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {

      "label": "Run Debug Server",
      "type": "shell",
      "command": "${workspaceRoot}/.venv/bin/flask run -h 0.0.0.0 -p 5000",
      "group": {
          "kind": "build",
          "isDefault": true
       }
    }
  ]
}
```

Flask 开发服务使用环境变量来获取应用程序的入口点。 如 **使用环境变量** 一节所说，可以在 `.env` 文件中声明这些变量：



```
FLASK_APP=wsgi.py
FLASK_DEBUG=True
```

这样就可以使用快捷键 `Ctrl + Shift + B` 来执行任务了。


### 单元测试


VS Code 还支持单元测试框架 pytest、unittest 和 nosetest。启用测试框架后，可以在 VS Code 中单独运行搜索到的单元测试，通过测试套件运行测试或者运行所有的测试。


例如，可以这样启用 pytest 测试框架：



```
"python.unitTest.pyTestEnabled": true,
"python.unitTest.pyTestPath": "${workspaceRoot}/.venv/bin/pytest",
```

注意，项目的虚拟环境中需要安装有 pytest，此示例方能有效。


![](/data/attachment/album/201809/08/083200aedrig7ii79tii3w.gif)




---


via: <https://fedoramagazine.org/vscode-python-howto/>


作者：[Clément Verna](https://fedoramagazine.org) 选题：[lujun9972](https://github.com/lujun9972) 译者：[idea2act](https://github.com/idea2act) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Visual Studio Code, or VS Code*,* is an open source code editor that also includes tools for building and debugging an application. With the Python extension enabled, *vscode* becomes a great working environment for any Python developer. This article shows you which extensions are useful, and how to configure VS Code to get the most out of it.


If you don’t have it installed, check out our previous article, [Using Visual Studio Code on Fedora](https://fedoramagazine.org/using-visual-studio-code-fedora/):

### Install the VS Code Python extension

First, to make VS Code Python friendly, install the Python extension from the marketplace.

Once the Python extension installed, you can now configure the Python extension.

VS Code manages its configuration inside JSON files. Two files are used:

- One for the global settings that applies to all projects
- One for project specific settings

Press **Ctrl+,** (comma) to open the global settings.

#### Setup the Python Path

You can configure VS Code to automatically select the best Python interpreter for each of your projects. To do this, configure the *python.pythonPath* key in the global settings.

// Place your settings in this file to overwrite default and user settings. { "python.pythonPath":"${workspaceRoot}/.venv/bin/python", }

This sets VS Code to use the Python interpreter located in the project root directory under the *.venv* virtual environment directory.

#### Use environment variables

By default, VS Code uses environment variables defined in the project root directory in a *.env* file. This is useful to set environment variables like:

PYTHONWARNINGS="once"

That setting ensures that warnings are displayed when your program is running.

To change this default, set the *python.envFile *configuration key as follows:

"python.envFile": "${workspaceFolder}/.env",

### Code Linting

The Python extension also supports different code linters (*pep8*, *flake8*, *pylint*). To enable your favorite linter, or the one used by the project you’re working on, you need to set a few configuration items.

By default *pylint *is enabled. But for this example, configure *flake8:*

"python.linting.pylintEnabled": false, "python.linting.flake8Path": "${workspaceRoot}/.venv/bin/flake8", "python.linting.flake8Enabled": true, "python.linting.flake8Args": ["--max-line-length=90"],

After enabling the linter, your code is underlined to show where it doesn’t meet criteria enforced by the linter. Note that for this example to work, you need to install *flake8* in the virtual environment of the project.

### Code Formatting

VS Code also lets you configure automatic code formatting. The extension currently supports *autopep8*, *black* and *yapf*. Here’s how to configure *black*.

"python.formatting.provider": "black", "python.formatting.blackPath": "${workspaceRoot}/.venv/bin/black" "python.formatting.blackArgs": ["--line-length=90"], "editor.formatOnSave": true,

If you don’t want the editor to format your file on save, set the option to *false* and use **Ctrl+Shift+I** to format the current document. Note that for this example to work, you need to install *black* in the virtual environment of the project.

### Running Tasks

Another great feature of VS Code is that it can run tasks. These tasks are also defined in a JSON file saved in the project root directory.

#### Run a development flask server

In this example, you’ll create a task to run a Flask development server. Create a new Build using the basic template that can run an external command:

Edit the *tasks.json* file as follows to create a new task that runs the *Flask* development server:

{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "Run Debug Server", "type": "shell", "command": "${workspaceRoot}/.venv/bin/flask run -h 0.0.0.0 -p 5000", "group": { "kind": "build", "isDefault": true } } ] }

The Flask development server uses an environment variable to get the entrypoint of the application. Use the *.env *file to declare these variables. For example:

FLASK_APP=wsgi.py FLASK_DEBUG=True

Now you can execute the task using **Ctrl+Shift+B**.

### Unit tests

VS Code also has the unit test runners *pytest, unittest, *and *nosetest* integrated out of the box. After you enable a test runner, VS Code discovers the unit tests and letsyou to run them individually, by test suite, or simply all the tests.

For example, to enable *pytest:*

"python.unitTest.pyTestEnabled": true, "python.unitTest.pyTestPath": "${workspaceRoot}/.venv/bin/pytest",

Note that for this example to work, you need to install *pytest* in the virtual environment of the project.

## Sugreeva

Is Microsoft Entering Open Source world from back which hated for many years ?

Why you are encouraging VS Code while there are other Superb Editors available ?

## Clément Verna

Hi Surgreeva

I just happen to use VS code on my Python projects and I find it great :). If you would like to write an article on how to use your favorite editor the magazine will be more than happy to publish it 🙂

## Boris

I second that. I’ve used several IDE for python and VS Code is quite good. And with ability to work with different languages and on different platforms it is my top choice now.

## Jim

Many of us open source folks actually enjoy VS Code.

Thanks to the author for this post, it was super helpful in getting my Python environment setting up.

## Bangjie Deng

I’m going to learn gnu emacs, but it is difficult to find a more vivid and modern introduction as organized in the Fedora Magazine. I hope the Fedora Magazine publishes more articles about more editors from the FREEDOM world.

## Paul W. Frields

VS Code is free and open source, MIT licensed. Let’s stop pretending it’s any less of a contribution. https://github.com/microsoft/vscode

## Trueman

VS Code the product has a different license than the code in the repository.

https://github.com/Microsoft/vscode/issues/60

## Bruce

Hi

Thanks for writing this. I’m already a fan of VS code for other languages. This way I don’t have to learn yet another IDE — wonderful as it may be.

## cmdr

Really disappointed that Fedora Magazine would be promoting a product from Microsoft, of all places. As a long time Fedora user (since Core 1, and Redhat Linux before that) I am very concerned. There are much better options for Python development that we should be focusing on to promote a healthy ecosystem.

## judovana

hi cmdr!

I’m on fedora corfe since FC4,and usually I would second you. But even you must agree thatm$ have chnaged a bit…

Anyway, do you mind to share your pythin IDE choices? I ended on Pycharm at the end. However it still have some issues I dont like. So I htink I will give VS a shot….

## Matt Davis

VSCode uses the MIT License so I think this is both free as in beer and free as in freedom. Not to get in to a philosophical argument here but MS publishing software using “freedom” licenses I think means we won at least some small victory.

You can access the vscode repo at https://github.com/Microsoft/vscode if you would like.

## Rafael

I use vs code with fedora.

I created script to facilitate after installation in venv.

https://github.com/RafaelBorring/project-to-vscode

## Sugreeva

Dear Clement Verna and others who are good at VS Code please use it in Windows Environment.

I appreciate the statements of cmdr… Like you I also been observing Fedora from Core 1. It is not the matter of License. It is the matter of Monopoly that made Microsoft $$$s. Microsoft recently announced about joining to Linux Forum. But you see… In Windows, Go to Manage->Disk management and see the status of ext4 partitions…. It just changed earlier stand of Unrecognized type to Healthy Partition. Never told that it is of ext4 type. Why ?

github might have took its birth by those who had disliked monoploy. Now Microsoft purchased it. Microsoft only knows how to swallow. To counter the popularity of Java they came up with .net. Sun Microsystems fought with Microsoft for many years in court regarding Java…

So… Let them offer gold or diamond… Microsoft is Microsoft… Don’t let Microsoft to purchase you and me also…

Thank you all…

## Matthew Bunt

I personally thank Microsoft for making a noticeable effort be more friendly to the open source community. As long as the license is free, it doesn’t matter so much who writes the code. In fact, I would say having a project supported by a large company is more likely to produce a better product than a project with very few resources and this seems to be the case with VS Code.

There is no doubt Microsoft employs some talented developers. The more they allow those developers to work on open source projects, the more it helps both Microsoft and our beloved community.

I look forward to more great developer software from Microsoft that I can run on my favorite operating system, Fedora.

## Frederik

I’ve tried several times to like VS Code and still haven’t found it to be better than any of the many other IDE and IDE like programs we have available.

I’m not entirely sure why VS Code exists, except that it’s a subtle way to acustom developers to

the Microsoftway of doing things — one that I am definitely not a fan of.Yes, it’s a victory that VS Code has been released under an MIT license, but I fear that this may be a trojna horse (or at least an attempt at one).

## Steve

Well, I’ve never been a big fan of the clearly stated terms of use regarding Microsoft (and other vendors) software products when purchasing them. Especially the point of ownership, which as stated usually doesn’t transfer to the user/purchaser. The benefits seen from an organization the size of Microsoft tend to get outweighed by the drive to satisfy shareholder return on investment. Certainly the mass of the organization would indicate a nominal percentage of exceptional talent being employed, and utilizing their talents in the open source community would/should/could be a benefit to all. There will be a reason for them to be involved in the community, it may not be nefarious, however it likely is profit driven. Which comes around to the point of the existence of the open source community in the first place, which for me boils down to freedom of choice to use and modify as seen fit, and that would include community editions of software, such as VS Code if I so desire. If they play nice in the sandbox, welcome them. If not, give them the boot.

## Neil Darlow

If Microsoft want to publish Free Software then it’s all to the good. The source code is there to examine if you feel paranoid about back-doors and nefarious practices.

I think it’s good that Microsoft are now accepting that Free Software exists and they are suppoting the technology on their OS too (I refer to EXT4). As for Windows not identifying an EXT4 partition, what’s the big deal? Many Windows users wouldn’t use or know what an EXT4 partition is let alone appreciate what EXT4 means.

The use of VSCode on Fedora is a personal choice. Use it or don’t it’s entirely up to you but don’t try to put others off using a piece of software based on conspiracy theories.

## Ranjan

License : MIT

License : Multiple, see https://code.visualstudio.com/license

Can we expect an MIT version of vscode in fedora repositories anytime soon?

Only the source code of VSCode is MIT licensed. The package that gets installed from their repositories are still covered under Microsoft Software License Terms which says.

Ref: https://code.visualstudio.com/license

You may not:

* remove, minimize, block or modify any notices of Microsoft or its suppliers in the software;

* share, publish, or lend the software, or provide it as a hosted solution for others to use, or transfer the software or this agreement to any third party.

## ganner rhysode

This is an interesting observation. I have been reading through the comments and I understand both sides. The author is merely stating their editor of choice, maybe this will encourage others to publish their setups as well and offer some alternatives for those who are new to all this or those who are looking for a change.

## Yazan Al Monshed

that nice

## lobocode

Thank you for writing this article. Very good to foment the open source, collaboration.

## Creep73

If you want to test and immediate opt-out from telemetry sending to Microsoft.

File -> Preferences -> and put it into User

{ “telemetry.enableTelemetry”: false, “telemetry.enableCrashReporter”: false, }

## Creep

And one more tip.

Here is OSS version of VSCode https://beta.flathub.org/apps/details/com.visualstudio.code.oss

Not MS one https://flathub.org/apps/details/com.visualstudio.code

Details are in https://github.com/flathub/com.visualstudio.code.oss/issues/6#issuecomment-380152999