Python and VS Code

15

In this post, I’m going to share a few things I’ve learned after working with Python in Visual Studio Code over the last year. The VS Code Preview was released a year ago this week, and I had started using it a few weeks earlier when I had joined the Cross-Platform Tools team at Microsoft. (Trivia: VS Code was code-named Ticino back then.) I’ve written many Python programs in VS Code since then, and have grown to really like it. I feel like it does what I need and stays out of my way, and my productivity has been improved significantly by the things I’ll cover below.

I say “stays out of my way” because I’m a longtime text editor fan, and have always preferred lightweight text editors to IDEs (integrated development environments). I was a big fan of Brief in the 90s, and wrote many complex macros for it to support assembly language and Visual FoxPro development. Then I dabbled in Visual Studio when I started at Microsoft ten years ago, but in recent years I’ve used Sublime for most things, and I enjoyed its blazing fast performance and clean simple UI. Then I switched to VS Code last year, and it feels just right to me. It’s a simple fast text editor, but has a rich and growing set of features, as well as a robust extensibility architecture that enables developers to build interesting new tooling for various languages and scenarios.

By the way, if you prefer to use a full-featured IDE, there is a great free open source plugin called Python Tools for Visual Studio that will turn Visual Studio — even the free Community edition — into a very powerful IDE for Python development. The Microsoft team behind that plugin has a great blog for Python developers as well, the Python Engineering at Microsoft blog. It offers great Intellisense and cross-language debugging options, support for multiple Python versions and virtual environments, and many other features. But in this post, I’ll be focusing on a few tips for doing Python development in VS Code.

The Python Extension

There’s some very basic Python support built into VS Code, but to maximize your Python productivity you’ll want to install Don Jayamanne’s excellent Python extension. This free plugin provides a host of useful features: Python-aware Intellisense, auto-completion, hover tooltips to view function and method signatures, linting (I use Pylint, it also supports Pep8 and Flake8), debugging (including multi-threaded, web apps, and remote processes), code formatting, snippets, unit testing (unittest and nose), and more. It’s a popular extension, with over 86,000 users as of today:

PythonExtension

Installing the extension only takes a few seconds, and then you need to manually configure the full path to your Python interpreter as described here. Note that you can configure the pythonPath as a User setting (if you want to use the same Python interpreter/version for all projects) or Workspace setting (to vary Python version by project).

After the Python extension is installed and configured, you’ll find all sorts of things that just work as you’d expect. For example, here’s the syntax help that pops up when I’m using the csv.writer function from the Python standard library:

stdlibhelp

Note that you’ll also have shortcut keys for things like going to the definition of a function (F12), which works in your code, the standard library, or third-party packages you’ve installed. For more about these shortcuts, check out the Rich Languages Editing section of the Visual Studio Code Key Bindings reference.

The Python extension also provides common debugging tools such as breakpoints, a watch window, call stack, and so on. For more information about how VS Code approaches debugging in general, see Debugging in Visual Studio Code.

Configuring a “Build” Task

In addition to installing the Python extension, I like to configure a build task that runs the current Python program when I press Ctrl-Shift-B in VS Code. “Build” is a bit of a misnomer in this case, since the task is just launching the interpreter, but Python projects don’t need a build task so I’ve repurposed that hot key for something more useful to me.

To configure tasks in VS Code, press Ctrl-Shift-P (to get into the command window), then type configure task and press enter. This will open a tasks.json file in the .vscode subfolder of the current project, and you can replace the contents of tasks.json with this snippet to make Ctrl-Shift-B run the Python program you’re currently editing:

{
	"version": "0.1.0",
	"command": "python",
	"isShellCommand": true,
	"showOutput": "always",
	"args": ["${file}"]
}

With that task defined, when I press Cltr-Shift-B the output of a Python console app will appear in a pane below my source code in the VS Code user interface as shown here:

CtrlShiftB

It’s worth noting that I’m running this on Windows 10, and I have Python 3.5’s home directory in my search path so I can get away with using python as the command to launch the Python interpreter. If you’re using OS X or Linux, or using other Python versions, you may need to use a different command. Generally speaking, just use the same syntax you’d use at a command prompt and everything should work fine.

If you’d like to learn more about how to configure tasks in the tasks.json file, see the reference documentation for the JSON schema.

Running Tests

I like to use pytest for my tests, and currently the Python extension only supports unittest and nose for test integration. (Although pytest is apparently under consideration.) But it’s easy to configure a task to run pytest tests, so that’s what I do on projects where I’m using pytest.

For example, here’s a tasks.json file that defines a Ctrl-Shift-B build task to run the current Python program, and a Ctrl-Shift-T test task to run my pytest tests:

{
    "version": "0.1.0",
    "command": "cmd",
    "isShellCommand": false,
    "args": ["/c"],
    "tasks": [
        {
		// build task - Ctrl-B
		"taskName": "python",
		"isBuildCommand": true,
		"args": ["${file}"]
        },
        {
		// test task - Ctrl-T
		"taskName": "py.test",
		"isTestCommand": true,
		"args": ["-v"]
        }
    ]
}

Note the -v argument that I’ve provided for the test task, to provide verbose output that shows which tests have run. With this setup, you can press Ctrl-Shift-T to run your pytest tests for the current project, and the pytest output will appear in a pane in VS Code as shown here:

TestOutput

Note that the example tasks.json above is just one of many possible ways you can configure multiple tasks in VS Code. If you’d like to learn about other approaches, there’s some good information in this discussion on the VS Code repo: https://github.com/Microsoft/vscode/issues/981

Conclusion

That’s an overview of a few aspects of my current approach for working on Python projects in VS Code. I don’t use all of the tools available within VS Code; for example, VS Code has Git integration, but I prefer to do Git chores at the command line so I’ve never actually used it. I’ve also never used some features of the Python extension, such as code formatting, but that’s just a personal preference. There are also a few things I’d like to have that aren’t available yet. For example, support for Python virtual environments within my custom tasks in VS Code, which is apparently under development for the Python extension. But overall, I like the feel of working in VS Code on Python projects, and the experience just keeps getting better and better.

If you’re doing Python development on Windows, and you’re inclined to use a simple editor instead of a full-blown IDE, I strongly recommend taking a look at Visual Studio Code.

Share.

15 Comments

  1. Great information. I’ve been looking for more information on python with VS Code. One of the items I am trying to figure out is to attach to a python console for debugging. I was wondering if you have any tips??

  2. Thanks, glad it’s useful for you. Regarding debugging, I’ve configured my Python 3.5 for debugging in Don Jayamanne’s Python extension as covered here: https://github.com/DonJayamanne/pythonVSCode/wiki/Python-Path-and-Version. It seems to work, although I’ve not done much with it yet, mostly I’ve just used it to add variables to the watch window. I’ll do a follow-up post after I do some more with it, debugging is probably worth a detailed post of its own.

    • Great. Cool. I’m digging into it at as well. The goal I’m trying to figure out is to attach to a interactive console for debugging but not much luck yet. Looking forward to your article.

  3. Great information to me! I’m moving on to VScode these days. Do do you have any clue to make the outputs in a separate window? For example, those figures produced by matplotlib packages. Thank you very much!

    • Hey Ruibin – no, I’m not aware of any way to detach the output window or direct output to another window from within VS Code. I agree that would be useful; I’ll document it here if I find a way.

  4. Trying to conditionally to do a breakpoint and haven’t been able to figure it out.

    I in a loop check to see if a=’abc’ if so stop so I can debug.

    I know it has to be possible.

  5. thank you for sharing this info, i am gonna give vs code a run, have you ever worked with django debugging on here? i have managed to configure the task to run my django project with ctrl+shift+b but i am not able to stop on the breakpoints i have put.

    thank you!

  6. Thank you for sharing this valuable feedback!

    I’m wondering how VS Code can handle remote python interpreters? More or less complex python project requires virtual machine/Docker container for the development environment (to run tests and debug).

    Does VS Code require local python environment for code completion/linting?

    I’m looking for alternatives to running Vim/Neovim inside the development environment.

    Thank you in advance!

  7. Doug,
    My company has moved all of it’s production servers to Amazon cloud and their serverless architecture supports Python 2.7 so I’m wanting to learn more about Python.
    I’m a Network Admin and new to Python (about the closest I’ve come to programming is VB 6 back in the 90’s so my programming skills are gone.) I’ve setup Visual Studio 2015 Community for Python and it’s working, but a bit overwhelming for me. Do you think VS Code is a good editor for someone who’s new to Python and programming?

    • Hi Carlton, yes I think VS Code is a great editor for a person new to Python and programming. The UI is simple and straightforward, and it’s quick to load and generally stays out of your way. A full IDE experience like Visual Studio or PyCharm provides some extra features that can be useful, but I think it makes sense to start with a simple editor that provides syntax highlighting and then after a while you’ll know whether you need or want those more advanced features. my needs are fairly simple, and I use VS Code for almost all of my Python work.

Leave A Reply