Python in Visual Studio

So, you’re a long time user of Visual Studio who has heard all about Python from that annoyingly productive guy in the office, and you want to give it a try but you don’t know where to start. Well, help is at hand, because you can do all of your Python development, debugging and package management without ever leaving the comfort of Visual Studio, and that’s what I’ll guide you through in this post.

Installing Python

Installing Python is very straightforward as it has a Windows installer.

  • Download the latest version of Python and install it, making sure to check the option to add it to your PATH.

At the time of writing, the latest version is Python 3.5.1. If you know that you need a different version then by all means go ahead, but in general I’d advise you to go for the latest version of Python 3 unless you have a good reason not to.

Once the installer finishes, Python should be on your PATH.

  • Open a command prompt and type python to check that it is installed and on your PATH.

You should see a prompt similar to this:

C:\Users\Rod>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z
  • Press Ctrl-Z to exit.

Installing Python Tools for Visual Studio

Python Tools for Visual Studio (PTVS) turns Visual Studio into a highly capable Python IDE, with all of the features that you’d expect to find such as IntelliSense.

Creating a Python project in Visual Studio

To create a Python project in Visual Studio…

  • Open Visual Studio and go to File > New > Project…
  • Look for the Python tag under Templates and pick Python Application for the project type as we’re just creating a simple “hello, world” application.
  • Give the project a name, e.g., “hello_python”.
create_python_project
Creating a new Python project

Creating, running and debugging a Python program

Now you’re in a position to start writing some Python. Visual Studio has already added an empty Python file to the project, so open it and start editing.

If you haven’t used Python before then enter this…

def say_hello(name='world'):
    print('Hello, {}!'.format(name))

if __name__ == '__main__':
    name = input('What is your name? ')
    say_hello(name)

As you type, IntelliSense should kick in and start suggesting completions for you. If not, it is almost certainly because IntelliSense hasn’t finished building its completion db for this Python environment. You can check on its status by opening the Python Environments window (Tools > Python Tools > Python Environments) and selecting IntelliSense from the dropdown.

To run the program, press Ctrl F5 as you would with any other project. It will run and display its output in a console window.

PTVS has excellent debugger integration, so if you want to debug your program then set a breakpoint, just as you would with a C# application, then run the program with F5.

Installing packages – part 1

In much the same way that Visual Studio has nuget, Python has a package manager called pip. This is typically run from the command line, but Visual Studio wouldn’t be Visual Studio without allowing us to do everything from the IDE.

  • Go to Solution Explorer and open up Python Environments, which is immediately under your project.

This will display a list of packages that are installed in your Python environment that are additional to the built in packages that come with every Python distribution. On the PC that I’m using now, it shows the 4 packages that are installed in my global Python 3.5 environment, along with their versions.

global_python_solution_explorer
Packages in the global Python environment

If you wanted to install a new package at this point then you would right click on the environment name Python 3.5 (global default) then select Install Python Package… from the menu.

However, take a close look at the name of the environment. It contains the word global, alerting us to the fact that installing a package into this environment would in fact install the package into the global Python installation. In other words, we wouldn’t be installing a package just for our project or solution – we’d be installing it for all projects that use this version of Python.

Occasionally this might be exactly what you want or need, but it’s more likely that different projects will need different sets of packages. You could install everything into your global Python environment, but at some point you will encounter a dependency conflict.

And that’s where Python has another trick up its sleeve in the form of virtual environments.

Creating a virtual environment

In a sentence, a virtual environment is a copy of the Python executable and its packages in their own self-contained directory tree. This means that if we create a virtual environment then we can install packages into it without affecting the global Python installation.

In Solution Explorer, under your project’s name, you should see a section labelled Python Environments.

  • Right-click on Python Environments and select Add Virtual Environment…
  • Select the global Python interpreter that you want to base your new virtual environment on, select a location for it, then click Create.

By default, the new virtual environment will be installed into env in your project’s directory. This is sensible, as you will probably want to keep your environment with your project. There are also valid arguments for putting it elsewhere, but for our purposes keeping it with the project is fine.

create_venv2
Creating a virtual environment

The new virtual environment now appears under Python Environments in Solution Explorer. If you expand it then, as before, you’ll see a list of installed packages.

new_venv_in_solution_explorer2
Packages in the virtual environment

Now we have a virtual environment just for our project, so we can install packages into it without worrying if it is going to affect other environments.

For further information take a look at what the Python documentation has to say on the topic, or at the documentation on installing packages.

Installing packages – part 2

Now that we have a virtual environment, we can install packages for our project without polluting the global Python installation.

To install a package…

  • Right click on the Python environment in Solution Explorer.
  • Select Install Python Package… from the menu.
  • Type the name of the package, eg, requests, into the text field then click OK.
install_package
Installing the ‘requests’ package from PyPI

Once you click OK then pip will download the package and its dependencies from the Python Package Index (PyPI) and install it into the virtual environment.

Here I’ve chosen to install  requests which bills itself as “Python HTTP for Humans”. Go ahead and install it as we’ll use it in the next section.

Once the package has installed then it will show up in the list of installed packages.

Running Python interactively

Python has an interactive shell, where you can type Python code and execute it immediately. PTVS makes this shell available in Visual Studio, and naturally enough it enhances it with the Visual Studio magic of IntelliSense.

To open an interactive window…

  • Right click on the Python environment in Solution Explorer.
  • Select Open Interactive Window

You can run Python commands in the interactive shell.

  • Type the following into the interactive shell…
import requests
result = requests.get('http://www.bbc.co.uk')
result.status_code
result.headers

As you type, you’ll see IntelliSense kicking in. It also has pretty good help – watch what happens if you hover the mouse cursor above the word get for example.

Footnote

This post is partially in response to my colleague, Nicholas, who on Friday as I was leaving the office said to me, “Rod, I’ve finally decided to download and learn Python.” Like me, he spends a large part of his day job writing C# in Visual Studio. I felt it was important to get him off on the right foot with package management and virtualenvs, but I also knew that he would get on far better with Python if I could show him how to do everything from an environment that he knew well, rather than selling him on the merits of an alternative such as PyCharm.

Advertisements

One thought on “Python in Visual Studio

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s