Visual Studio Mac Python



  1. Visual Studio Community Edition Python
  2. Microsoft Visual Studio Mac
  3. Mac Visual Studio Code Python
  4. Visual Studio For Mac Tutorial

Dear Readers,

Jul 28, 2020 We need three things to install Visual Studio Code and the Python Extension on MAC. VS Code; VS Code Python extension; Python 3; Step 1 – Install VS Code. Click Download for MAC. Unzip the file you will get “Visual Studio Code.app”. Click Open if below mentioned window pops up. In this article, I am going to explain how to set up your Visual Studio Code for Python Development. Visual Studio Code or, popularly known as VS Code, is one of the free and open-source code editors developed by Microsoft and is mostly preferred by developers of all the major programming languages due to its flexibility and other integrated development tools like debugging, IntelliSense, etc.

In this post, I will explain steps to Install Visual Studio Code and the Python Extension on MAC.

+

We need three things to install Visual Studio Code and the Python Extension on MAC

  1. We need three things to install Visual Studio Code and the Python Extension on MAC. VS Code; VS Code Python extension; Python 3; Step 1 – Install VS Code. Click Download for MAC. Unzip the file you will get “Visual Studio Code.app”. Click Open if below mentioned window pops up.
  2. Jul 28, 2020 Start Visual Studio from within /Applications Now open the Command Palette (F1 or ⇧⌘P on Mac) and type shell command to find the Shell Command: Install 'code' command in PATH command. By starting VS Code in a folder, that folder becomes your “workspace”.
  3. In the Mac Terminal app, my base conda environment is active and when I run Python it correctly uses the Miniconda version of Python as shown below: In Visual Studio Code (VSCode), I have selected the Miniconda version of Python using the Python Interpreter setting. The correct version of Python and conda environment is shown at the bottom of.
  • VS Code
  • VS Code Python extension
  • Python 3

Step 1 – Install VS Code

1. Go To URL https://code.visualstudio.com

2. Click Download for MAC

3. Unzip the file you will get “Visual Studio Code.app”. Double click.

4. Click Open if below mentioned window pops up

Step 2 – Install Python Extension for VS Code

  1. Next, install the Python extension for VS Code from the Visual Studio Marketplace.

2. Click Continue – Visual Studio Code is required to install the extension

3. Click Open Visual Studio Code after clicking the optional checkbox for always allowing the market place to open visual studio code.

4. Click OK

5. Click Install

>> Installing

>> Installed

>> You may see this error in the bottom

Step 3 – Install a Python interpreter

Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.

1. On macOS, make sure the location of your VS Code installation is included in your PATH environment variable.

Click “Command + Shift + P”

On the search tab – type ” shell command” > Install code command in path will appear – click on that

Click OK

Enter Password

The system install of Python on macOS is not supported. Instead, an installation through Homebrew is recommended.

2. Install Homebrew

To install Home Brew in MAC- Run this command on terminal

Enter password

Once it is installed, you will see below messages

Step 4 Install Python

To install Python using Homebrew on macOS use brew install python at the Terminal prompt.

Step 5 Verify the Python installation

To verify that you’ve installed Python successfully on your machine, run one of the following command :

python3 –version

If the installation was successful, the output window should show the version of Python that you installed.

I faced a issue here – It was showing old version of my python

I used below command to resolve it, but unsuccessful

$ brew install pyenv

$ pyenv install 3.8.5

$ pyenv global 3.8.5

$ pyenv version

It was again showing the same version

Now I tried

brew link python@3.8

It was showing error – so I removed few files

rm ‘/usr/local/bin/2to3’

rm ‘/usr/local/bin/idle3’

rm ‘/usr/local/bin/pydoc3’

rm ‘/usr/local/bin/python3’

rm ‘/usr/local/bin/python3-config’

And finally I run the command again and it was successful

ravidubey@Ravis-MacBook-Pro ~ % brew link python@3.8

Linking /usr/local/Cellar/python@3.8/3.8.5… 25 symlinks created

ravidubey@Ravis-MacBook-Pro ~ % python3 –version

Python 3.8.5

Step 6 Start VS Code in a project (workspace) folder

Using a command prompt or terminal, create an empty folder called “hello”, navigate into it, and open VS Code (code) in that folder (.) by entering the following commands:

In case you face issue, run this command

  • Move Visual Studio .app file from any location to application folder
  • Remove the current link with sudo rm /usr/local/bin/code
  • Start Visual Studio from within /Applications
  • Now open the Command Palette (F1 or ⇧⌘P on Mac) and type shell command to find the Shell Command: Install 'code' command in PATH command.

By starting VS Code in a folder, that folder becomes your “workspace”. VS Code stores settings that are specific to that workspace in .vscode/settings.json, which are separate from user settings that are stored globally.

Alternately, you can run VS Code through the operating system UI, then use File > Open Folder to open the project folder.

Step 7 Select a Python interpreter

Python is an interpreted language, and in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.

Visual studio python environment mac

From within VS Code, select a Python 3 interpreter by opening the Command Palette (⇧⌘P), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):

The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don’t see the desired interpreter, see Configuring Python environments.

Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda), for example Python 3.7.3 64-bit ('base':conda)

Selecting an interpreter sets the python.pythonPath value in your workspace settings to the path of the interpreter. To see the setting, select File > Preferences > Settings (Code > Preferences > Settings on macOS), then select the Workspace Settings tab.

Note: If you select an interpreter without a workspace folder open, VS Code sets python.pythonPath in your user settings instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.

Step 8 Create a Python Hello World source code file

From the File Explorer toolbar, select the New File button on the hello folder:

Name the file hello.py, and it automatically opens in the editor:

By using the .py file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.

Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.

Now that you have a code file in your Workspace, enter the following source code in hello.py:

When you start typing print, notice how IntelliSense presents auto-completion options.

IntelliSense and auto-completions work for standard Python modules as well as other packages you’ve installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg variable contains a string, IntelliSense provides string methods when you type msg.:

Feel free to experiment with IntelliSense some more, but then revert your changes so you have only the msg variable and the print call, and save the file (⌘S).

For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.

You may have to install pylint using the command

brew install pylint

Step 9 Run Hello World

It’s simple to run hello.py with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.

The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):

There are three other ways you can run Python code within VS Code:

  • Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):
  • Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.
  • From the Command Palette (⇧⌘P), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.

Step 10 Configure and run the debugger#

Let’s now try debugging our simple Hello World program.

First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing F9. Alternately, just click in the editor’s left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.

Next, to initialize the debugger, press F5. Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.

Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.

These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.

The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg variable appears in the Local pane.

A debug toolbar appears along the top with the following commands from left to right: continue (F5), step over (F10), step into (F11), step out (⇧F11), restart (⇧⌘F5), and stop (⇧F5).

The Status Bar also changes color (orange in many themes) to indicate that you’re in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.

To continue running the program, select the continue command on the debug toolbar (F5). The debugger runs the program to the end.

Tip Debugging information can also be seen by hovering over code, such as variables. In the case of msg, hovering over the variable will display the string Hello world in a box above the variable.

You can also work with variables in the Debug Console (If you don’t see it, select Debug Console in the lower right area of VS Code, or select it from the menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:

Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. “Hello World” appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.

If you restart the debugger, the debugger again stops on the first breakpoint.

To stop running a program before it’s complete, use the red square stop button on the debug toolbar (⇧F5), or use the Run > Stop debugging menu command.

For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.

Tip: Use Logpoints instead of print statements: Developers often litter source code with print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn’t stop the program. For more information, see Logpoints in the main VS Code debugging article.

Step 11 Install and use packages

Let’s now run an example that’s a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)

Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py, and paste in the following source code:

Tip: If you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter.

Next, try running the file in the debugger using the “Python: Current file” configuration as described in the last section.

Unless you’re using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, “ModuleNotFoundError: No module named ‘matplotlib'”. Such a message indicates that the required package isn’t available in your system.

To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Integrated Terminal (⌃⇧`). This command opens a command prompt for your selected interpreter.

A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:

Note: For additional information about virtual environments, see Environments.

  1. Create and activate the virtual environment Note: When you create a new virtual environment, you should be prompted by VS Code to set it as the default for your workspace folder. If selected, the environment will automatically be activated when you open a new terminal.
  2. For macOS/Linuxpython3 -m venv .venv
  3. Run command in the folder source .venv/bin/activate
  4. Select your new environment by using the Python: Select Interpreter command from the Command Palette.
  5. Install the packages# python3 -m pip install matplotlib
  6. Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:
  7. Once you are finished, type deactivate in the terminal window to deactivate the virtual environment.

Ref – https://code.visualstudio.com/docs/python/python-tutorial

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 Community Edition Python

In this article, you’ll learn about Python development in Visual Studio Code, including how to:

  • Install Visual Studio Code
  • Discover and install extensions that make Python development easy
  • Write a simple Python application
  • Learn how to run and debug existing Python programs in VS Code
  • Connect Visual Studio Code to Git and GitHub to share your code with the world

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.

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.

Installing and Configuring Visual Studio Code for Python Development

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:

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

The VS Code UI is well documented, so I won’t rehash it here:

Extensions for Python Development

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:

  • Support for Python 3.4 and higher, as well as Python 2.7
  • Code completion with IntelliSense
  • Automatic use of conda and virtual environments
  • Code editing in Jupyter environments and Jupyter Notebooks

Visual Studio Code extensions cover more than just programming language capabilities:

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

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.

Of course, you may discover other useful extensions as you use VS Code. Please share your discoveries and settings in the comments!

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:

You can find and install any of the extensions mentioned above in the same manner.

Visual Studio Code Configuration Files

One important thing to mention is that Visual Studio Code is highly configurable through user and workspace settings.

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.

Start a New Python Program

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

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.

No matter how you get there, you should see a VS Code window that looks similar to the following:

Once a new file is opened, you can being entering code.

Entering Python 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:

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?

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.

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:

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.

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.

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:

Here’s the full code for a basic Sieve of 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.

Running Python Code

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:

You should see the Terminal pane appear at the bottom of the window, with your code output showing.

Python Linting Support

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:

  • pylint
  • flake8
  • mypy
  • pydocstyle
  • pep8
  • prospector
  • pyllama
  • bandit

The Python linting page has complete details on how to setup each linter.

Note: The choice of linter is a project workspace setting, and not a global user setting.

Editing an Existing Python Project

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:

  • Create a folder to hold the project (which may include a new GitHub project)
  • Change to the new folder
  • Create the initial Python code using the command code filename.py

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.

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.

Microsoft Visual Studio Mac

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.

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

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.

Testing Support

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.

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.

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.

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.

Debugging Support

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:

  • Automatic variable tracking
  • Watch expressions
  • Breakpoints
  • Call stack inspection

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.

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.

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:

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.

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.

Git Integration

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:

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:

  • Commit files to Git
  • Push changes to, and pull changes from, remote repos
  • Check-out existing or create new branches and tags
  • View and resolve merge conflicts

All of this functionality is available directly from the VS Code UI:

VS Code will also recognize changes made outside the editor and behave appropriately.

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:

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.

Conclusion

Mac Visual Studio Code Python

Visual Studio Code is one of the coolest general purpose editors and a great candidate for Python development. In this article, you learned:

  • How to install VS Code on any platform
  • How to find and install extensions to enable Python-specific features
  • How VS Code makes writing a simple Python application easier
  • How to run and debug existing Python programs within VS Code
  • How to work with Git and GitHub repositories from VS Code

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.

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.

The author sends thanks to Dan Taylor from the Visual Studio Code team at Microsoft for his time and invaluable input in this article.

Visual Studio For Mac Tutorial

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]