简体   繁体   中英

ModuleNotFoundError in jupyter notebook when importing a module after conda install

I'm trying to use conda to set up one of my projects. I installed openCV by conda install -c conda-forge opencv . When I run conda list , I can see openCV in the list. Running python -i and then import cv2 works, but when I open up Jupyter Notebook and navigate to that folder (I have to do it this way because running jupyter notebook in the directory also pulls up an error), and open up a notebook which imports cv2, I get an error. Why is this happening, and how would I solve it? Any kind of help will be greatly appreciated.

So as I said before, I wasn't able to start Jupyter Notebook from the command line, I had to start it from the start menu and navigate to my folder. Because of that, my notebook wasn't working in the conda environment that I created. I fixed that by running python -m ipykernal install --user --name <env_name> --display-name "<display_name>" . I had to conda install ipykernel . It works now. Thanks for the other answers.

Usually that indicates that the notebook is running with a different Python or in a different environment from Python in the command prompt. Check sys.executable to see which Python it's running in, and sys.path to see where it's looking for imports

Everybody says that pip installing from notebook is not the best practice, but maybe for a fast try it would do the thing:

# Install a conda package in the current Jupyter kernel
import sys
!conda install --yes --prefix {sys.prefix} packagename

# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install packagename

I used it from Install python packages on Jupyter Notebook and it worked for me.

Step 1: Activate environment before running
conda activate <environment-name>

Step 2: Install ipykernel
conda install -c anaconda ipykernel

Step 3: Add the conda environment to ipykernel
ipython kernel install --name <environment-name> --user

Step 4: Install your package
conda install -c conda-forge opencv

References:
How to add your Conda environment to your jupyter notebook in just 4 steps

Conda environments not showing up in Jupyter Notebook

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM