I’m running into an issue with VS Code and Python on my Mac. Since macOS comes with Python 2 pre-installed, I’m using both Python 2 and Python 3 on my system. When I try to open a directory in VS Code from my terminal using code .
, I get this error:
Your PYTHONPATH points to a site-packages directory for Python 3.x, but you are running Python 2.x!
PYTHONPATH is currently: :/usr/local/lib/python3.7/site-packages
You should unset PYTHONPATH to fix this.
/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code: line 10: ./MacOS/Electron: No such file or directory
Error Code:
code# For opening VS Code from terminal
PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin:$PATH"
export PATH
# Path for Python packages (numpy, pandas, beautifulsoup)
PYTHONPATH=$PYTHONPATH:/usr/local/lib/python3.7/site-packages
export PYTHONPATH
I’d appreciate any tips on how to resolve this conflict so VS Code can work seamlessly with Python.
To solve the issue you’re facing, you’ll need to handle two key points:
- Unset or conditionally set
PYTHONPATH
depending on which Python version you are using, to avoid the conflict between Python 2 and Python 3 packages. - Correct the VS Code path in
.zshrc
to ensure it’s pointing to the right executable.
Solution:
Update .zshrc
for Conditional PYTHONPATH
and VS Code Path
- Unset
PYTHONPATH
for sessions where you are using Python 2, or set it conditionally for Python 3 sessions only. - Check and correct the VS Code executable path.
Your updated .zshrc
should look like this:
Correct Code:
code# For opening VS Code from terminal
export PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin:$PATH"
# Conditionally set PYTHONPATH only if using Python 3.x
if [[ "$(python3 --version 2>/dev/null)" ]]; then
export PYTHONPATH="/usr/local/lib/python3.7/site-packages"
else
unset PYTHONPATH # Unset PYTHONPATH if using Python 2
fi
Explanation:
- VS Code Path Update: The
PATH
line here adds the VS Code application binary path to your shell’s search path, allowing you to runcode .
from the terminal. - Conditional
PYTHONPATH
: This check (if [[ "$(python3 --version 2>/dev/null)" ]]
) first verifies if Python 3 is installed and accessible. If true, it setsPYTHONPATH
to Python 3’s site-packages directory. Otherwise, it unsetsPYTHONPATH
, preventing conflicts when running Python 2.
Applying the Changes:
After updating .zshrc
, run the following command to apply the changes:
codesource ~/.zshrc
Testing the Solution:
- Open a terminal and try running Python 3 by typing
python3
. - Verify that
PYTHONPATH
points to the Python 3 directory: codeecho $PYTHONPATH
- Run VS Code from the terminal with
code .
to check if the error is resolved.
This approach should allow you to use VS Code without the PYTHONPATH
conflict and ensure smooth switching between Python 2 and Python 3 environments.