Using Homebrew python3 with both homebrew packages and pip/pip3 packages in Visual Studio Code for Mac OS - python-3.x

I am currently trying to setup Visual Studio Code on Mac OSX 10.13.6 for coding in python3. I'd like to avoid using multiple virtual environments for my different python3 scripts and instead have them all run using:
(1) the same homebrew installation of python3
(2) accessing installed python packages in:
homebrew packages list
pip3 installed package list
pip installed packages list.
First, I first installed python3 using homebrew:
$ brew info python
python: stable 3.7.7 (bottled), HEAD
Interpreted, interactive, object-oriented programming language
https://www.python.org/
/usr/local/Cellar/python/3.7.7 (4,062 files, 62.4MB)
...
Python has been installed as
/usr/local/bin/python3
...
You can install Python packages with
pip3 install <package>
They will install into the site-package directory
/usr/local/lib/python3.7/site-packages
Second, I installed my required packages using homebrew:
$ brew list
cmake libffi p11-kit
dcraw libheif pandoc
dlib libidn2 pcre
...
jasper numpy webp
...
And other packages using pip and pip3:
$ pip list
DEPRECATION:...
Package Version
-------------------------------------- --------
altgraph 0.10.2
...
numpy 1.8.0rc1
...
zope.interface 4.1.1
$
$ pip3 list
Package Version
------------------ -------
appnope 0.1.0
...
numpy 1.18.2
pandocfilters 1.4.2
parso 0.5.2
pexpect 4.7.0
pickleshare 0.7.5
pip 20.0.2
pomegranate 0.12.2
...
scipy 1.4.1
Third, I opened Visual Studio Code and in "Preferences" -> "Settings" and set "Python:Python Path" to the homebrew python3 installation as noted above /usr/local/bin/python3.
See this screenshot:
Next, I added /usr/local/lib/python3.7/site-packages per the homebrew install of python3 to the Visual Studio Code Settings file using:
"python.autoComplete.extraPaths": [
"/usr/local/lib/python3.7/site-packages" ]
Finally, I selected my python interpreter in Visual Studio Code as /usr/local/bin/python3 and tried to run the following 2-lines of imports in a .py script as per the screenshot below. Note that the interpreter is Python 3.7.0 64-bit given by the bottom left corner of the VS Code window.
And after all of that, ended up with this output after clicking the "Play" button to run the code in the top right corner of VS Code:
[Running] python -u "/Users/...bayes_net_nodes.py"
Traceback (most recent call last):
File "/Users/...bayes_net_nodes.py", line 1, in <module>
import numpy as np
ModuleNotFoundError: No module named 'numpy'
[Done] exited with code=1 in 0.037 seconds
What would be the most simple way to configure VS Code so I can run python3 scripts that have access to the all the packages I've installed across my system without using virtual environments? Thank you!
Note: One workaround that seems to work, and I'm not sure why is if I put a shebang at the top of my script #! /usr/local/bin/python3 and my output then looks like this:
[Running] /usr/local/bin/python3 "/Users/...bayes_net_nodes.py"
[Done] exited with code=0 in 0.051 seconds
Which is odd, because that's different than the output above where I didn't use the shebang but both python interpreters according to VSCode are indeed /usr/local/bin/python3

I was able to reproduce your problem.. but only when I use Code Runner to run.
Those kind of Output logs with [Running] and [Done] is Code Runner.
The play button is also not green, indicating Code Runner because the default is green.
Now, for the fix!
You'll notice that it executed your script using python -u. That python would be whatever python means on your system, which for me is the default Python 2.7. Basically, it's not your Homebrew Python3 with numpy.
Code Runner has a default set of "executors" which tells it which executable to use for which language. Search it for in your settings as "code-runner Executor Map":
Open your settings.json, enter code-runner.executorMap, then let it auto-complete with the default. You'll then see a long list of mappings between language and executor. Look for the one for python:
"code-runner.executorMap": {
"javascript": "node",
...
"python": "python -u",
"perl": "perl",
...
}
And there it is: python -u, the same one it used to run your script.
If you want to continue using Code Runner, simply change it to the whichever python interpreter you want to use. In your case, it should be /usr/local/bin/python3:
"code-runner.executorMap": {
...
"python": "/usr/local/bin/python3",
...
}
It should now work:
The reason it works with a #! /usr/local/bin/python3 shebang is because Code Runner has a setting that it respects the file's shebang (code-runner.respectShebang) which is true by default.
If you don't want this extra step of setting-up Code Runner, you can simply disable (or uninstall it). All the steps you already did (setting python.pythonPath, selecting the interpreter, and clicking that Play button) would have already worked just fine with Microsoft's Python extension. See the official docs on running Python files, selecting environments, and debugging.

Related

Tensorflow installed can't be imported

I'm trying to import tensorflow. But even after installing it, it doesn't seem to be recognized.
>conda create -n tf tensorflow
>conda activate tf
(tf)>pip install --ignore-installed --upgrade tensorflow==1.15 --user
...
Successfully installed absl-py-0.9.0 astor-0.8.1 gast-0.2.2 google-pasta-0.2.0 grpcio-1.28.1 h5py-2.10.0 keras-applications-1.0.8 keras-preprocessing-1.1.0 markdown-3.2.1 numpy-1.18.2 opt-einsum-3.2.0 protobuf-3.11.3 setuptools-46.1.3 six-1.14.0 tensorboard-1.15.0 tensorflow-1.15.0 tensorflow-estimator-1.15.1 termcolor-1.1.0 werkzeug-1.0.1 wheel-0.34.2 wrapt-1.12.1
(tf) C:\Users\antoi\Documents\Programming\Covent Garden\covent_garden_ds>python3 app.py
Traceback (most recent call last):
File "app.py", line 4, in <module>
from tensorflow.keras.callbacks import ModelCheckpoint
ModuleNotFoundError: No module named 'tensorflow'
Python3 is there:
(tf) C:\Users\antoi\Documents\Programming\Covent Garden\covent_garden_ds>where python3
C:\Users\antoi\AppData\Local\Microsoft\WindowsApps\python3.exe
It's not the one I should be using, isn't it?
What version of Python are you running? In order to both successfully import and run the Tensorflow module, you must have the 64 bit version of Python installed. If you are using the latest version of Python, which to the best of my knowledge is 3.8.2, completely uninstall that version of Python, and downgrade to the latest Python version with 64 bit support.
If you follow the output of pip --version to find where your anaconda files are located, you can find the anaconda python executable, usually about two directory levels higher (if pip is in C:\example\anaconda\lib\site-packages, then python is probably in C:\example\anaconda) and use a full path to that python executable to run the file like C:\example\anaconda\python app.py. Or you could update your path environment variable to replace C:\Users\antoi\AppData\Local\Microsoft\WindowsApps\ with the directory containing the anaconda python executable
I've had this same exact issue (but on macOS) several times before I realized what was wrong, and I've seen several others have this issue too. I wish there was a way Python could somehow better regulate this to make sure the default executables for pip and python are always in sync

easy SublimeText question regarding pygame module

I've been using SublimeText on OSX without issue... until I tried to import pygame. A simple few lines of code like:
print("Hello")
import sys
import pygame
gets the following output:
Hello
Traceback (most recent call last):
File "/Users/andrewjmiller/Desktop/python_work/new_file.py", line 5, in <module>
import pygame
ImportError: No module named pygame
[Finished in 0.0s with exit code 1]
[shell_cmd: python -u "/Users/andrewjmiller/Desktop/python_work/new_file.py"]
[dir: /Users/andrewjmiller/Desktop/python_work]
[path: /Library/Frameworks/Python.framework/Versions/3.8/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Users/andrewjmiller/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]
But... I do have pygame installed, as evidenced here:
iMac:~ AndyTheAdmin$ python3 -m pip install --user pygame==2.0.0.dev6
Requirement already satisfied: pygame==2.0.0.dev6 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (2.0.0.dev6)
I've uninstalled and reinstalled SublimeText3. What should I try next?
You're falling victim to the difference between Python 2 and Python 3. In particular, note the line in the Sublime diagnostic output that says what command it was that failed:
[shell_cmd: python -u "/Users/andrewjmiller/Desktop/python_work/new_file.py"]
The Python.sublime-build file that ships with Sublime tells the OS to execute the command python.
In your example where it works (or rather where you get confirmation that the library is installed):
iMac:~ AndyTheAdmin$ python3 -m pip install --user pygame==2.0.0.dev6
Here you're executing python3. Dollars to donuts if you were to type python --version in the terminal, it's Python 2 that Sublime is executing. The different versions of Python keep their packages in different locations, which is why it works in one place and not the other.
Assuming that this is the case, the solution is to use a build that executes python3 instead. If you're already using a custom build system, then you can modify it directly. If you're using the build that ships with Sublime, the easiest way to make a new build is:
Use View Package File from the command palette and open Python/Python.sublime-build to see what the existing build system looks like, and copy the entire thing to the clipboard.
Use Tools > Build System > New Build System, replace the content with what you copied above, then swap the python for python3 in the two shell_cmd lines so that they execute the version that you expect.
Save the file in the location that Sublime defaults to (should be your User package) as a sublime-build file with an appropriate name.
Once you save, the Build system will be made available. You can either select it from Tools > Build System to use it directly, or if you have the build system in that menu set to Automatic the next time you do a build Sublime should prompt you to pick the build to use since there is now new builds.

How do I install curses library in my editor?

I cannot install the curses library in my Editor. Is there some other way to make sure I have the library installed and can import it?
I'm trying to build a tictactoe game using venv, in Pycharm Community Edition. I imported curses in the directory where my scripts are located using command prompt. I can import curses in IDLE editor. However, there is no package called curses in the Settings->Project Interpreter.
pip install curses‑2.2‑cp36‑cp36m‑win_amd64.whl
this throws an error:
Requirement 'curses-2.2-cp36-cp36m-win_amd64.whl' looks like a
filename, but the file does not exist
curses-2.2-cp36-cp36m-win_amd64.whl is not a supported wheel on this
platform.
Edited the configurations and checked the checkbox with emulate terminal in output console, still won't work.
You should use:
pip install https://download.lfd.uci.edu/pythonlibs/n5jyqt7p/curses-2.2.1+utf8-cp37-cp37m-win_amd64.whl
The section of the pip command line installer:
cp37 == CPython 3.7
So you need the appropriate whl install file for your installed Python environment.

Unable to import Libraries even though Installed in Anaconda on Pycharm

I am using Ubuntu 18.10(dual Boot win10), I have installed anaconda (conda version- 4.6.7) on ubuntu. After this Installation I installed Pycharm via snap on Command Prompt. Since Pycharm(version - 2018.3.5) didnt Detect my python Location automatically I set the python Interpreter via
Adding Location ->System Interpreter (As I didn't want any Venv) -> Path
But when I try to import opencv in Pycharm it says
ModuleNotFoundError: No module named 'cv2'
Python3.6 in Anaconda Bin is shown to which I have linked in Pycharm (I have also tried other Python files there as well but no luck)
When I run in Terminal: python3 -c 'import sys; print(sys.path)'
It shows:
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6
/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/local
/lib/python3.6/dist-packages/setuptools-39.1.0-py3.6.egg', '/usr/lib`/python3
/dist-packages']
So could anyone help me out in this?? Thank You in Advance!!
Edit 1:
I am also unable to access any of the libraries from terminal Itself. So Could anyone help me with that as well. Should I export path of this Python in Anaconda bin folder to bashrc file in Ubuntu?
Edit 2:
The libraries affected is not just opencv. There are few other Libraries like Portaudio which are affected as well along with Opencv

Jupyter notebook doesn't find an import when ipython does [duplicate]

I've gotten myself into some kind of horrible virtualenv mess. Help?!
I manage environments with conda. Until recently, I only had a python2 jupyter notebook kernel, but I decided to drag myself kicking and screaming into the 21st century and installed a python3 kernel; I forget how I did it.
My main (anaconda) python defaults to 2.7.
So here I am, merrily trying to use beautiful soup from inside my shiny new python3 kernel, and I don't seem to be able to do anything to get at whatever environment it's finding packages in. Viz (all from notebook):
from bs4 import BeautifulSoup
-> ImportError: No module named 'bs4'
Ok, fine, I'll install it using shell magic. Right? Right?
! pip install bs4
--> Collecting bs4
Downloading bs4-0.0.1.tar.gz
Requirement already satisfied (use --upgrade to upgrade): beautifulsoup4 in /Users/[MY-USER]/anaconda/lib/python2.7/site-packages (from bs4)
[...]
Successfully built bs4
Installing collected packages: bs4
Successfully installed bs4-0.0.1
from bs4 import BeautifulSoup
-> ImportError: No module named 'bs4'
Oh no. Does it think I'm in a 2.7 env even though I'm running a python3 kernel? That won't do.
! conda info --envs
--> # conda environments:
#
flaskenv /Users/[MY-USER]/anaconda/envs/flaskenv
mesa /Users/[MY-USER]/anaconda/envs/mesa
py35 /Users/[MY-USER]/anaconda/envs/py35
root * /Users/[MY-USER]/anaconda
Ok, I can fix that. One of those is a 3.5 env.
! source activate py35
--> prepending /Users/[MY-USER]/anaconda/envs/py35/bin to PATH
! conda install beautifulsoup4
--> Fetching package metadata .......
Solving package specifications: ..........
# All requested packages already installed.
# packages in environment at /Users/[MY-USER]/anaconda:
#
beautifulsoup4 4.4.1 py27_0
concerning...
! pip install bs4
--> Requirement already satisfied (use --upgrade to upgrade): bs4 in /Users/[MY-USER]/anaconda/lib/python2.7/site-packages
more concerning...
from bs4 import BeautifulSoup
-> ImportError: No module named 'bs4'
ARRGH!!! headdesk Am I going to have to kill the kernel in order to fix this (and re-run a bit of work)? Is killing the kernel even going to work? How do I get my jupyter kernel to know what environment it's supposed to be running under?
thanks!
This is a tricky part of ipython / Jupyter. The set of kernels available are independent of what your virtualenv is when you start jupyter Notebook. The trick is setting up the the ipykernel package in the environment you want to identify itself uniquely to jupyter. From docs on multiple ipykernels,
source activate ENVNAME
pip install ipykernel
python -m ipykernel install --user --name ENVNAME --display-name "Python (whatever you want to call it)"
If you only want to have a single Python 3 kernel, from the conda environment, just use python -m ipykernel install --user and it will reset the default python to the one in the virtualenv.
And yes, you will need to restart the kernel and re-run the prior steps.
See Also Using both Python 2.x and Python 3.x in IPython Notebook
#tschundler's solution works perfectly if your environment has already been created.
If you want to change the default kernel at the creation of your virtual environment and avoid any manual configuration, you just need to add jupyter at the end of the conda command:
conda create --name ENVNAME python=PYTHONVERSION jupyter
The correct kernel will then be used when you use ipython or jupyter notebook.
In my case somehow jupyter wasn't able to 'pick' the virtual environment's python. So I had to edit ~/.local/share/jupyter/kernels/{my_env_name}/kernel.json
and add path to the interpreter
in the argv key.
There is also an easy way here
workon my-virtualenv-name # activate your virtualenv, if you haven't already
pip install tornado==4.5.3
pip install ipykernel==4.8.2
You should now be able to see your kernel in the IPython notebook menu: Kernel -> Change kernel and be able to switch to it (you may need to refresh the page before it appears in the list). IPython will remember which kernel to use for that notebook from then on.
This worked for me. source
pip install --user ipykernel
python -m ipykernel install --user --name=myenv
Output
Installed kernelspec myenv in /home/user/.local/share/jupyter/kernels/myenv
and go to above directory
open kernel.json
{
"argv": [
"/home/user/anaconda3/envs/myenv/bin/python", # path to your virtual environment python
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "myenv",
"language": "python"
}
I know this is an old question, but nobody has mentioned nb_conda_kernels, which was made to solve this problem. You must have it installed in the environment from which you launched the running notebook, and any other environment which has kernel/s installed (ipykernel, r-irkernel, etc ) will be available as an option (Start Preferred Kernel):
Sharing my experience here, in case someone made the same mistake:
TL;DR
In VSCode I created the virtual environment from an Ubuntu terminal but forgot to activate the WSL extension too. Once I activated the WSL extension, I was able to change the Jupyterkernel to my virtual environment.
Full explanation
Using VSCode I work with the WSL extension (see here). I created my virtual environment from an Ubuntu terminal [Created a new terminal and selected 'Ubuntu (WSL)'] and then went to my Jupyter notebook to change my kernel, but it did not appear in the list.
I tried the solution proposed above of adding the path to kernel.json in my virtual environment, adapting to my case (I don't use conda) but I was surprised to see that the folder bin in my environment did not have a file named python.
The solution was to activate the WSL extension: lower right corner > click on the arrows (Open a remote connection) > reopen folder in WSL.
After this, I could see in the explorer two new entries in the bin folder for Python and Python3 (the arrow on the right side seem to indicate it's a symbolic link).
Virtual environment now shows the python symbolic links
Then I went to my Jupyter notebook and changed the kernel to my virtual environment.
In the end, I did not have to change the path in kernel.json.
P.S: The above is my understanding of my problem and the solution given my non-existing knowledge about Linux, so any comments to complement/improve this answer are very welcome!

Resources