Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

python - Cannot import modules in jupyter notebook; wrong sys.path

I am having a problem importing modules in my iPython/Jupyter notebook. The problem fundamentally lies in where the sys.path is pointing to.

From the iPython/Jupyter notebook, sys.executable returns:

'/usr/bin/python'

However, from the command line, it returns:

'//anaconda/bin/python'

I have tried un-installing and re-installing anacondas, but the problem still remains.

I have also tried augmenting $PYTHONPATH in my bash_profile to include //anaconda/bin/python, but this doesn't resolve it.

Is there anyway to change the sys.path in my jupyter notebook permanently, without simply using sys.path.append(...)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same issue. After going through many (like way too many) solutions to this issue found elsewhere, I manage to figure out a solution that at least works in my case.

Step1: check the correct executable path of the anaconda environment.

Go on command line, activate the conda environment that is problematic, and check the correct executable path for the environment.

conda activate {envronment name};
then on python console, (>>>)import sys;sys.executable

For instance on Linux it will be /media/{username}/{path-to}/anaconda3/envs/{environment name}/bin/python

Step2: correct the executable path for jupyter sessions.

From command line, check the path where kernel.json of your problematic conda environment is located.

jupyter kernelspec list

For instance on Linux it will be: /home/{username}/.local/share/jupyter/kernels/{environment name}

Open the kernel.json located in that folder and replace the incorrect executable path, as shown below.

{
 "argv": [
  "REPLACE-THIS-WITH-THE-CORRECT-EXECUTABLE-PATH",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "environment name",
 "language": "python"
}
 

Hope this works in your case too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...