How to use VS Code for your Python projects

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:

Using Visual Studio Code on 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.

For Developers

20 Comments

  1. 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 ?

    • 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.

  2. 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.

  3. 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.

  4. 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….

  5. 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.

  6. Rafael

    I use vs code with fedora.
    I created script to facilitate after installation in venv.
    https://github.com/RafaelBorring/project-to-vscode

  7. 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…

  8. 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.

  9. 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 Microsoft way 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).

  10. 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.

  11. 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.

  12. Ranjan

    sudo dnf info atom | grep License
    License      : MIT
    sudo dnf info code | grep License
    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.

  13. Yazan Al Monshed

    that nice

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

Leave a Reply

The opinions expressed on this website are those of each author, not of the author's employer or of Red Hat. Fedora Magazine aspires to publish all content under a Creative Commons license but may not be able to do so in all cases. You are responsible for ensuring that you have the necessary permission to reuse any work on this site. The Fedora logo is a trademark of Red Hat, Inc. Terms and Conditions

%d bloggers like this: