How do I access updated Python 3.9 in VS Code via command line?

Viewed 3855

I just downloaded VS Code this week and have run into a problem accessing different versions of Python.

When I run a python file called set.py from the command line via python set.py, VS Code is accessing the Python 2.7 version that came with my MacBook. When I run python --version it confirms that VS Code is using Python 2.7.16.

However, when I right-click in the editor and select Run Python File In Terminal it appears to be using the updated version 3.9.4. I have tested this by using an fstring (available in 3.9 but not in 2.7). The fstring code throws an error in the first method but clears fine in the second. Here's my code:

s = set()

s.add(1)
s.add(2)
s.add(3)

print(f"The set has {len(s)} elements.")

And here's my terminal with the results of both methods shown.

Does anyone know what exactly is going on, and how I can execute python files via the command line?

TIA

Specs:

I am running VS Code 1.55.2 and have downloaded Python 3.9.4 to my MacBook Pro running Big Sur 11.2.3

I have also downloaded the Python extension in VS Code and have selected Python 3.9.4 64-bit as my interpreter.

1 Answers

On macOS and linux, you will have a system python that tends to be old and you don't want to touch it because there are system utilities that rely on it.

You will also have the user-installed python, which here is python 3.9.

If the system python is python2, then the command python will typically invoke python2 and the command python3 will invoke python3.

In VS Code on Windows, when you launch a terminal window from the IDE, it will activate the interpreter/environment you've chosen for your project (typically by CTRL-SHIFT-P and then Python: Select Interpreter). I've noticed on Linux that it will not do this (and this may also be the case on macOS), so if I want to use a specific version or environment, I need to specify it or activate it as my first command in the terminal with something like conda activate myenvname.

Unlike in the terminal, VS Code will use the selected interpreter if you run code directly from the IDE (using Run Without Debugging or Control + F5).

Related